Copyright: Borland C++ 5.02 copyright (c) 1997 Borland International, Inc.


What's New in ObjectComponents for Borland C++ 5.01
What’s New in ObjectComponents for since Borland C++ 5.0

ObjectComponents has been enhanced in several ways since Borland C++ 5.0:

The TAutoVal class supports the Variant data type. So now you can use Variant values in your automation controllers, which makes it easier to communicate with many automation servers. And you can expose properties and methods that use the Variant data type in your automation servers, which makes them more accessible to automation controllers, including non-C++ automation controllers.

The TAutoVal class supports the TNoArg data type. So now from your automation controllers you can call methods that have many optional parameters more easily. For optional parameters that you don’t want to specify, simply pass a TNoArg object.

Two new examples, AUTOEXCL and AUTOWORD, show how to communicate with Microsoft Excel and Microsoft Word respectively using automation controllers built with ObjectComponents. These examples include pre-generated proxies that you can use in your own automation controllers. You can find the these examples in the BC5\EXAMPLES\OCF\ directory.


What is ObjectComponents?

See also

Microsoft's OLE 2 operating system extensions require the programmer to implement a variety of interfaces depending on the tasks an application undertakes. Borland has developed an OLE engine, already used in several of its commercial applications, that simplifies the programmer's job by implementing a smaller set of high-level interfaces on top of OLE. The engine resides in a library called BOCOF.DLL. The BOCOF support library provides default implementations for many standard OLE interfaces.

C++ programmers can make use of the OLE support in BOCOF.DLL through a set of new classes collectively called the ObjectComponents Framework (OCF). Instead of implementing OLE-style interfaces, you create objects from the ObjectComponents classes and call their methods. Your own classes can gain OLE capabilities simply by inheriting from the ObjectComponents classes.

The ObjectComponents classes implement OLE-style interfaces for talking to the BOCOF support library. Your programs reach OLE by calling methods from ObjectComponents classes. When OLE sends information to you, ObjectComponents sends messages to your application by calling the appropriate member functions of an event-handling class. The event-handling classes have default implementations for all the OLE messages. You can override the default event handlers selectively to modify your application's responses.

ObjectComponents is not part of the ObjectWindows Library. That means C++ programs that don't use ObjectWindows can still take full advantage of ObjectComponents for linking, embedding, and automation. But ObjectWindows can simplify your work even more. ObjectWindows 5.0 introduces new classes such as TOleWindow and TOleDocument that inherit from ObjectComponents classes to bring OLE support into Borland's C++ application framework. An ObjectWindows application that uses the Doc/View model doesn't need to use ObjectComponents directly at all. A few simple changes to your Doc/View program will have you linking and embedding almost instantly. Programs that don't use the Doc/View model can do the same thing with just a little more work.


OLE 2 features supported by ObjectComponents

See also

The following list summarizes the OLE 2 capabilities that ObjectComponents gives your applications.

OCX container support: new classes make it easy to embed OCX controls in your applications.

Linking and embedding: to embed data from one application in the document of another, ObjectComponents gives you classes to represent the data in the object and an image of the data for drawing on the screen. The data must be separate from its graphical representation because OLE transactions are sometimes handled by different programs. When the container asks the server for an object to embed, the server must provide data and a view of the data. The server can also be asked to edit the object even after it is embedded and to read or write the object to and from the container's document file. The ObjectComponents classes handle both sides of these negotiations for you.

Clipboard operations: the default event handlers for the ObjectComponents messages handle cutting and pasting for you. If you add to your menus standard commands such as Insert Object and Paste Link, ObjectComponents will implement them for you.

Drag and drop operations: the default event handlers for ObjectComponents messages help you here, too. If the user drops an OLE object on your container's window, ObjectComponents inserts it in your document. If the user double-clicks the embedded object, ObjectComponents activates it. If the user drags the object, ObjectComponents moves it.

Standard OLE 2 user interface: OLE defines standard user interface features and asks OLE programmers to comply with them. Built into ObjectComponents are dialog boxes for commands like Insert Object, Paste Special, and Paste Link; a pop-up menu that appears whenever the user right-clicks an embedded object; and an item on the container's Edit menu that always shows the verbs (server commands) available for the active object. ObjectComponents even arranges to modify the container's window if the server takes over the container's tool bar, status bar, and menus for in-place editing.

Compound files: The TOcStorage class encapsulates file input and output to compound files. If you convert an ObjectWindows Doc/View application into an ObjectComponents container, the document writes itself to compound files automatically, creating storages and substorages within the file as needed.

EXE and DLL servers: ObjectComponents lets you construct your OLE server as either a standalone executable program or as an in-process DLL server. DLL servers respond to clients more quickly because a DLL is not a separate process. OLE doesn't have to serialize calls or marshall parameters to communicate between a DLL server and its client.

Automation: ObjectComponents permits C++ classes to be automated without structural changes to the classes themselves. It accomplishes this with nested classes that have direct access to the existing class members. These nested classes instantiate small command objects that reach the members through standard C++ mechanisms, avoiding the use of restrictive, non-portable stack manipulations. The command objects support hooks for undoing, recording, and filtering automation commands. A program can even send itself automation commands using standard C++ code.

Type libraries: A type library describes for OLE all the classes, methods, properties, and data members available for controlling an automated application. Once you create an automation server, you can ask ObjectComponents to build and register the type library for you.

Registration: OLE requires applications to register themselves with the system by providing a unique identifier string. For servers, this string and much other information must be recorded in the system's registration database as part of the program's installation process. With ObjectComponents, all you have to do is list all the information in one place using macros. Every time your server starts up, ObjectComponents confirms that the database accurately reflects the server's status. When necessary, ObjectComponents records or updates registration entries automatically.

Localization: OLE servers need to speak the language of their client programs. If an automation server is marketed in several countries, it needs to recognize commands sent in each different language. A linking and embedding server registers strings that describe its objects to the user, and those too should be available in multiple languages in order to accommodate whatever language the user might request. If you provide translations for your strings, ObjectComponents uses the right strings at the right time. Add your translations to the program's resources and mark the original strings as localized when you register them. At run time, ObjectComponents quickly and efficiently retrieves translations to match whatever language OLE requests.


How ObjectComponents talks to OLE

See also

Fundamentally, all OLE interaction requires the implementation of standard OLE interfaces, such as IUnknown and IDispatch, as defined by the Component Object Model (COM). (COM stands for Component Object Model. COM is the standard that defines what an OLE object is.)

An Interface is just a set of related function prototypes forming an abstract base class. Every OLE object that implements the same interface can choose to implement the prescribed functions in its own way. All that matters is that the interface functions always accept the same parameters and always produce the same results. This makes it possible for any OLE object to call any standard function in any other OLE object that supports the interface.

Every OLE object must implement the IUnknown interface. One of the three functions in the IUnknown interface is QueryInterface. This common function implemented on all OLE objects lets you ask whether the object supports other interfaces that you want to use, such as automation interfaces or data transfer interfaces. This makes it possible for any OLE object to determine at run time what any other OLE object can do.

OLE defines a large number of standard interfaces that are notoriously tedious to implement. Borland's BOCOF support library defines an alternate set of custom COM interfaces that collectively provide an alternative interface to OLE programming, one conceived at a higher level of abstraction. Client objects of the support library must still implement IUnknown, as all COM objects must, but instead of other standard OLE interfaces such as IDataObject and IMoniker, they implement interfaces defined by BOCOF. The support library acts as an agent translating commands received through its custom interfaces into standard OLE. All the custom interfaces commands are carried out for you using standard OLE interfaces.

The custom interfaces in the BOCOF support library have names like IBContainer and IBDocument. You'll see them used if you look in the ObjectComponents source code. Because the support library is an internal tool and subject to change, its interfaces are not documented. The complete library source code, however, comes with Borland C++, so you can refer to it if you need to track the OLE interactions minutely. You can also modify and rebuild the support library, just as you can the ObjectWindows Library, if that suits your purposes.


How ObjectComponents talks to you

See also

Some of the ObjectComponents classes define COM objects. These objects are derived from TUnknown, an ObjectComponents base class that implements the IUnknown interface and handles details of aggregation (a way of combining several objects into a single functional unit). They also mix in other base classes that implement interfaces from the BOCOF support library.

The ObjectComponents objects that implement COM interfaces are called connector objects because they connect your application to OLE. TOcPart, for example, is the connector object that implements the interfaces a container must support for each OLE object (part) that is placed in its document. To embed an object in your document, you take information ObjectComponents gets from the Clipboard, a drop message, or the Insert Object dialog box, and you pass the information to the TOcPart constructor. Among other things, the constructor (indirectly) calls a BOCOF function to create an embedded OLE object. TOcPart holds the pointer to that object, queries it for interfaces, and stores the coordinates of the site where the part should be drawn. When you want the part to do something, you call TOcPart methods such as Activate and Save.


Linking and embedding connections

See also

A linking and embedding application always creates a TOcApp object (usually it is created for you). TOcApp is a connector object that implements interfaces every linking and embedding application needs. Another connector object that all linking and embedding applications create is the view object, either TOcView for a container, TOcxView for an OCX container, or TOcRemView for a server. You create one view object for each document you open. A view object is associated with the window where the document is drawn. The only other connector objects used for linking and embedding are TOcPart and TOcControl, which containers and OCX containers respectively create for each object deposited in their documents.

Communication through a connector object is not just one way. When you call methods on a connector object, the object calls through to OLE, but sometimes OLE needs to call you. For example, if a user chooses Insert Object and asks for an object from a server, OLE must invoke the server and ask it to create an object.

Of course the connector objects cannot call your functions the same way you can call theirs because they don't know anything about your code. When a connector object needs to communicate a request or a notification from OLE to you, it calls the appropriate member function of an event-handling object: TOcContainerHost for a container, TOcCtrlContainerHost for an OCX container, or TOcServerHost for a server. The event-handling object has a virtual member function for each possible OLE message. By implementing the virtual functions, you can control how your application responds to OLE messages.

The event-handling objects are new in this release of ObjectComponents. The objects make it easier to debug your applications since you can easily trace execution into OLE message handlers. However, you don’t need to change any of your existing code; ObjectComponents behaves as before with old applications, automatically generating messages that are sent to the application and view windows.

Communication from you to OLE happens through function calls to connector objects. Communication from OLE to you happens through calls to an event-handling object.

The initial wiring between you and ObjectComponents is established the first time the registrar object calls your factory callback function. The TOcApp object is bound to a window in TOleFrame::SetupWindow, or in the WM_CREATE handler of your main application.


Automation connections

See also

To support automation, ObjectComponents must identify exposed commands and arguments, attach type information to them, transfer values to and from the stack of VARIANT unions that OLE uses to pass values, and invoke your C++ functions when a controller sends a command. Once you set up the tables that describe what you want to expose, there is little in the automation process to customize or override. You never directly create or manipulate the connector objects for automation; ObjectComponents does it for you.

Advanced users might like to know that TServedObject is the class that implements IDispatch and ITypeInfo, that TTypeLibrary implements ITypeLib, and that TAutoIterator implements IEnumVARIANT. Of these, only TAutoIterator is exposed as a public part of ObjectComponents. The others are considered internal implementation.

To automate a class, ObjectComponents asks you to build two descriptive tables from macros: a declaration table and a definition table. A declaration table goes with the class declaration and declares which members are accessible to OLE. A definition table goes with the class implementation and assigns public names for controllers to use when invoking your functions. The automation macros also create nested classes within the automated parent, one for each exposed function or data member. The nested classes have an Invoke method that calls your function. Because the class is nested, it has direct access to your class through normal C++ mechanisms.

TServedObject is the connector that receives IDispatch commands from OLE and translates them into the appropriate Invoke calls. TServedObject finds the information it needs to do this in an object of type TAutoClass, which holds the symbol information from the automation tables. TServedObject receives dispatch IDs, looks them up in TAutoClass, uses the information it finds to extract arguments from the stack of VARIANT unions passed by OLE. Finally it calls Invoke on the appropriate nested command object.


Connector objects

See also

A few of the ObjectComponents classes implement COM interfaces. Most of the supported interfaces are not standard OLE interfaces; they are custom interfaces that communicate with OLE through the BOCOF support library. But like any COM object they do implement IUnknown (by deriving from TUnknown).

The classes that define COM objects for linking and embedding are TOcApp, TOcView, TOcRemView, and TOcPart. These classes are special because they connect your application to OLE. They are called connector objects. An ObjectComponents application must create connector objects in order to interact with other OLE applications.

Because they are COM objects, connector objects have one peculiarity: their destructors are protected so you cannot call delete to destroy them. Readers familiar with OLE will recognize that the connector objects have internal reference counts that track the number of clients using them. Often you are not the only user of your own connectors. For example, when a server creates a TOcRemView to paint an object in a container's window, the container becomes a client of the same object. The server must not destroy the view object until the container is through with it, otherwise OLE could end up attempting to address functions that no longer exist in memory.

The Component Object Model specifies that an object must maintain an internal reference count. When an object provides anyone a pointer to one of its interfaces, the object also increments its own reference count. When the client finishes with the pointer, it calls Release and the object decrements its reference count. As long as the count is greater than zero, the object must not be destroyed. When the count reaches 0, the object destroys itself.

ObjectComponents shields you from the details of reference counting. You never have to increment or decrement a reference count. You cannot delete COM objects, however, because the delete command pays no attention to the reference count. Instead, call the connector's ReleaseObject method.


Utility programs

Borland C++ 5.0 comes with some utility programs that simplify common OLE programming chores.

AppExpert

The most powerful tool in Borland C++ to help you with ObjectComponents programming is AppExpert. AppExpert generates a complete basic application according to your specifications. It fully supports both linking and embedding and automation. Use it to create containers, OCX containers, servers, and automation servers. ClassExpert helps you modify the generated code to make it do what you need.

The TargetExpert in the integrated development environment (IDE) also supports ObjectComponents. Click the option for OCF and TargetExpert automatically sets the right build options.

You can generate a complete OLE application almost instantly using AppExpert. AppExpert fully supports all the new features of ObjectComponents. To start an OLE application from scratch, simply choose Project|AppExpert from the IDE menu. For more information about AppExpert, consult the User's Guide.

The programs AppExpert creates use the ObjectWindows Library. If you are new to ObjectWindows, begin with the ObjectWindows Tutorial book.

AutoGen

Generates proxy classes for an automation controller. Scans the type library of an automated application and writes the source code for classes a controller uses to send commands automation commands.

DllRun

Launches a DLL server in executable mode. Any DLL server written with ObjectComponents can also run as a standalone application if you invoke it with DllRun. Running in executable mode sometimes makes it easier to debug the DLL. It also makes it possible to distribute a single program that your users can run either as an in-process server or as an independent application.

GuidGen

Generates globally unique identifiers for use in registering applications. Every server must have an absolutely unique ID. Containers need them in order to be link sources.

MacroGen

Generates automation macros for exposing functions with any number of arguments. MacroGen saves you from having to revise the predefined macros by hand to accommodate more arguments.

Register

Registers or unregisters any ObjectComponents EXE or DLL. Usually the applications register themselves if necessary when they run, or in response to command-line switches. Developers, however, sometimes need to register and unregister different versions of an application over and over. Register is especially useful for DLLs because you can't pass command-line switches to a DLL.

WinRun

A background program that makes it possible to launch Windows programs from the command line prompt in a DOS box. WinRun makes it possible to run GUI programs (such as Register) from a make file.

The source code for all the utilities but WINRUN is in the OCTOOLS directory.


Where to find more information

You can find information about programming with ObjectComponents in the online Help, in the printed manuals, and in the directories of sample programs.

Throughout the documentation, OLE refers to OLE 2.0 unless version 1 is indicated explicitly.

Books

The chapters that follow describe how to build programs that perform all these functions.

Chapter Title	Topic

Support for OLE in Borland C++	Overview of ObjectComponents

Creating an OLE container	How to build an application that receives OLE objects in its documents

Creating an OLE server	How to build an application that creates OLE objects for containers to use

Automating an application	How to build an application that other programs can control

Creating an automation controller	How to build an application that controls other applications

For complete reference material covering all the new OLE-related classes and macros in ObjectComponents andObjectWindows, see the ObjectWindows Reference Guide.

The ObjectComponents material in this book and in the ObjectWindows Reference Guide is also in the online Help for Borland C++.

The ObjectWindows Tutorial develops a sample application from scratch. The later steps use add OLE container, server, and automation capabilities.

Online Help

Borland C++ includes three online Help files covering the OLE API.

Help file	Topic

OCF.HLP	ObjectComponents chapters from the ObjectWindows Programmer's Guide and the ObjectWindows Reference Guide.

OWL.HLP	Reference material for new OLE-enabled classes in ObjectWindows.

OLE.HLP	OLE 2 overviews and reference. For the most part, ObjectComponents makes knowledge of OLE interfaces unnecessary, but if your application requires advanced programming at the OLE interface level, then you might find this file useful.

Example programs

One of the best ways to learn about programming is to study working code. Borland C++ comes with a variety of sample programs that use ObjectComponents, including:

AutoCalc: an automation server; draws a calculator onscreen and lets a controller click the buttons.

 	Book: an OCX container.

 	CallCalc: an automation controller to manipulate the calculator in AutoCalc.

CppOcf: Three-step linking and embedding tutorial that starts with a simple C++ program, turns it into a container, and then into a server.

Localize: Pulls translated strings from XLAT resources to reflect language settings.

RegTest: Registers, validates the registration, and unregisters.


Turning an application into an OLE automation server

See also

Follow these steps to turn an application into an OLE automation server using ObjectComponents:

1. Include ObjectComponents header files.

2. Create a registration table.

3. Create a registrar object.

4. Declare automatable methods and properties.

5. Define automatable methods and properties.

6. Compile and link the automation server.

Later, you can enhance your server by localizing symbol names, combining C++ objects, exposing collections, invalidating deleted objects, or creating a type library.

Note:	The AutoCalc example in the EXAMPLES/OCF/AUTOCALC directory illustrates many of the above steps. AutoCalc draws a calculator on the screen and lets the user click buttons to perform calculations. AutoCalc automates its classes so that an automation controller can send commands to do the same things a user does.


Including header files (automation server)
Step 1: Including ObjectComponents header files (automation server)

An automation server must include the following header files:

#include <ocf/automacr.h>   // definition and declaration macros

#include <ocf/ocreg.h>      // TRegistrar class

The file list is short because an automation server does not need many of the ObjectComponents classes used for linking and embedding.


Creating a registration table (automation server)
Step 2: Creating a registration table (automation server)

See also

An automation server must set five pieces of information in the application's registration table: its class ID, program ID, name, description, and command-line arguments for invoking the automation server.

To create a registration table, use BEGIN_REGISTRATION macro. The following code shows the registration table for AutoCalc (\OCF\EXAMPLES directory):

BEGIN_REGISTRATION(AppReg)

  REGDATA(clsid,      "{877B6200-7627-101B-B87C-0000C057CE4E}")

  REGDATA(progid,     "Calculator.Application")

  REGDATA(appname,    "AutoCalc"

  REGDATA(description,"Automated Calculator 1.2 Application")

  REGDATA(cmdline,    "/Automation")

END_REGISTRATION


Creating a registrar object (automation server)
Step 3: Creating a registrar object (automation server)

See also

An automation server needs a registrar object. Applications that support only automation without linking and embedding should create a TRegistrar object; objects the support automation with linking and embedding should create a TOcRegistrar object.

To create a registrar object, declare a static pointer to hold the TRegistrar*. (Use the TPointer<> template to ensure that the registrar object is properly deleted when the program ends.)

TPointer<TRegistrar> Registrar;    // initialized at WinMain or LibMain

Then in the main procedure, you should create the registrar object and call its Run method. The following code shows the creation of the registrar object in the AutoCalc example (\OCF\EXAMPLES directory):

try {

   ::Registrar=new TRegistrar(AppReg,TOcAutoFactory<TCalc>(),

                              string(cmdLine), hInst);

   TAutoCommand::SetErrorMsgHook(ErrorLookup);

   if (!::Registrar->IsOptionSet(amAnyRegOption))

      ::Registrar->Run();

   ::Registrar = 0;  // deletes registrar by replacing pointer

   return 0;

}

catch (TXBase& x) {

   ::MessageBox(0, x.why().c_str(), "OLE Exception", MB_OK);

The first parameter of the TRegistrar constructor is the application registration structure, conventionally named AppReg. The second parameter is a factory callback function. The example uses a factory template to create the callback. For an automation server that doesn't use ObjectWindows, the appropriate template is TOcAutoFactory.

The call to IsOptionSet determines whether the application was passed a command-line switch asking the application to register itself in the system registration database and then quit. If not, the application calls Run. The registrar then calls the factory callback, where the message loop resides. When Run returns, the application has ended.


Declaring automatable methods and properties
Step 4: Declaring automatable methods and properties

See also

Automating a class requires building two tables, one in the class declaration and one in the class implementation. The first table is called the automation declaration, and it declares which members of the class a controller can reach. The second table is called the automation definition, and it defines public names that a controller uses to reach each exposed class member. This section tells how to build an automation declaration.

The automation declaration belongs inside the declaration of an automated class. It begins with the macro DECLARE_AUTOCLASS and includes one entry for each class member that you choose to expose. The macros add nested classes that ObjectComponents instantiates to process commands received from OLE. They do not alter the structure or size of the original class.

This sample automation declaration exposes functions and data members of a C++ class that mimics a calculator:

DECLARE_AUTOCLASS(TCalc)

  AUTODATA  (Accum,   Accum,     long,  )

  AUTODATA  (Opnd,    Opnd,      long,  )

  AUTODATA  (Op,      Op, short, AUTOVALIDATE(Val>=OP_NONE && Val<=OP_CLEAR) )

  AUTOFUNC0 (Eval,    Eval,      TBool, )

  AUTOFUNC0V(Clear,   Clear,            )

  AUTOFUNC0V(Display, Display,          )

  AUTOFUNC0V(Quit,    Quit,             )

  AUTOFUNC1 (Button,  Button,    TBool, TAutoString,)

  AUTOFUNC0 (Window,  GetWindow, TAutoObject<TCalcWindow>,  )

  AUTOFUNC1 (LookAt,  LookAtWindow, long, TAutoObject<const TCalcWindow>,)

  AUTODATARO(MyArray, Elem,      TAutoObjectByVal<TMyArray>,)

The automated class is called TCalc. Each AUTOFUNC or AUTODATA macro exposes one member of TCalc. Some of the TCalc member functions are Eval, Clear, Display, and Quit. Its data members include Accum, Opnd, Op, and Elem. TCalc also has other members that are not automated and are therefore excluded from the declaration table.

No termination macro is needed for an automation declaration. The END_AUTOCLASS macro that closes an automation definition is not used here. Also, each line of the declaration ends with a closing parenthesis, not with punctuation.

Note:	The automation declaration should appear at the end of a class declaration because the macros can modify the access specifier. If you put the declaration anywhere else, be sure to follow it immediately with an access specifier (public, protected, or private).

Writing declaration macros

Each of the macros within an automation declaration describes a single method or property that other programs can manipulate. The different macros expose different kinds of class members. AUTOFUNC1, for example, exposes a member function that takes one parameter. AUTOFUNC2V exposes a function that takes two parameters and returns nothing (void). AUTOPROP exposes a property through Set and Get functions that insert or retrieve a single value. AUTODATA exposes a data member that the controller can read and modify directly.

The general form of the automation macros is this:

MACRONAME( InternalName, FunctionName, ReturnType, ArgumentType, Options )

Some of the macros don't use all five parameters. AUTOFUNC1V, for example, doesn't have a ReturnType because the function has a void return. AUTOFUNC0 doesn't have any arguments, while AUTOFUNC2 has two different arguments. But whatever parameters are relevant appear in the order shown.

InternalName is an identifier you assign to each automatable property or function. It is used internally by ObjectComponents for keeping track of the members. The only other place you ever use the internal name is in the corresponding entry of the class's automation definition table. The internal name is a unique identifier for the member. (the names used in source code are not necessarily unique. They can be overloaded, for example.)

FunctionName is the name you use in your source code to refer to the same property or function. FunctionName can be any expression that evaluates to a function call. The expression must, however, be defined within the scope of the automated object. ObjectComponents attempts to reach the function through the this pointer.

The internal and function names should be the same unless the function name is overloaded or uses indirection. For example, suppose a class contains a data member that points to another object:

TObject* MyObject;

To expose a function call like MyObject->MyFunction, you should supply an internal name that does not use indirection. In this case, a good choice would be MyFunction.

AUTOFUNC0V( MyFunction, MyObject->MyFunction, )

If a function is overloaded, use the same function name for all versions but give each a different internal name. ObjectComponents can distinguish the overloaded functions by the return types and argument types in the parameters that follow.

The ReturnType and ArgumentType parameters can be any fundamental C type, such as int or char, or a pointer to any fundamental type. Some  pointers, however, require special handling. If the data type is a string (type char*), declare it to be a TAutoString instead. If the data type is a pointer or a reference to a C++ object, then declare it using the TAutoObject<> wrapper. The type substitutions help ObjectComponents convert between C++ data types and the VARIANT union type that OLE uses. Pointers and object references are hardest to convert because they refer to data that is not in the variable itself. The TAutoString and TAutoObject classes provide type information for the conversion so that ObjectComponents can pass the right information between server and controller applications.

The TCalc example shows how to use TAutoObject. One of the functions TCalc exposes is GetFunction, which returns a reference to a TCalcWindow object.

AUTOFUNC0 (Window, GetWindow, TAutoObject<TCalcWindow>, )

When it declares TCalcWindow as the return type, it makes use of the TAutoObject template to create a smart, self-describing pointer to a TCalcWindow object.

Providing optional hooks for validation and filtering

The final parameter of every automation macro names a hook function to be called whenever OLE calls the exposed class member. A hook is code that executes every time anyone uses a particular class member. ObjectComponents supports hooks to record commands, undo commands, validate command arguments, and override a command's implementation. Hooks are always optional.

To install a hook, use one of these macros as the last parameter to any automation declaration:

AUTOINVOKE

AUTORECORD

AUTOUNDO

AUTONOHOOK

AUTOREPORT

AUTOVALIDATE

Each macro receives a single parameter containing code to execute. The form of the required macro varies with its function.

To validate arguments, for example, the code should be a Boolean expression. The Op data member of TCalc holds an integer that identifies an operation to perform, such as addition or subtraction. The automation declaration installs a hook to be sure that Op is not assigned a value outside the legal range of operator identifiers.

AUTODATA(Op, Op, short, AUTOVALIDATE(Val>=OP_NONE && Val<=OP_CLEAR))

AUTOVALIDATE introduces the expression to execute for validation. Within the validation expression, use the name Val to represent the value received from the controller. When used to validate function arguments, AUTOVALIDATE uses the names Arg1, Arg2, Arg3, and so on.

Whenever any automation controller attempts to set a value in the Op data member, ObjectComponents verifies that the new value falls within the range OP_NONE to OP_CLEAR. If passed an illegal value, ObjectComponents cancels the command and sends OLE an error result.

The expression passed to AUTOVALIDATE can include function calls.

AUTODATA(Op, Op, short, AUTOVALIDATE(Val>=OP_NONE && NotTooBig(Val))

Now ObjectComponents calls NotTooBig whenever a controller attempts to modify Op.

bool NotTooBig(int Val) {

  return (Val <= OP_CLEAR)

}


Defining external methods and properties
Step 5: Defining external methods and properties

In addition to declaring which of its members are automatable, an automated class must also create a second table of macros to assign public symbols for referring to the exposed methods and properties. The public symbols are what other applications see. They become the controller's interface to an automated OLE object.

Behind the scenes, ObjectComponents links the public names to the C++ object or objects that you create to implement the OLE object. The automation declaration table identifies which class members to expose, and the automation definition table assigns them names.

The automation definition belongs with the class implementation. It begins with the DEFINE_AUTOCLASS macro and ends with END_AUTOCLASS. Here's the automation definition for TCalc:

DEFINE_AUTOCLASS(TCalc)

  EXPOSE_PROPRW(Opnd,      TAutoLong,  "Operand",      "@Operand_", HC_TCALC_OPERAND)

  EXPOSE_PROPRW_ID(0,Accum,TAutoLong,  "!Accumulator", "@Accumulator_",

        HC_TCALC_ACCUMULATOR)

  EXPOSE_PROPRW(Op,        CalcOps,    "Op",           "@Op_", HC_TCALC_OPERATOR)

  EXPOSE_METHOD(Eval,      TAutoBool,  "!Evaluate",    "@Evaluate_", HC_TCALC_EVALU ATE)

  EXPOSE_METHOD(Clear,     TAutoVoid,  "!Clear",       "@Clear_", HC_TCALC_CLEAR)

  EXPOSE_METHOD(Display,   TAutoVoid,  "!Display",     "@Display_", HC_TCALC_DISPLA Y)

  EXPOSE_METHOD(Quit,      TAutoVoid,  "!Quit",        "@Quit_", HC_TCALC_QUIT)

  EXPOSE_METHOD(Button,    TAutoBool,  "!Button",      "@Button_", HC_TCALC_BUTTON )

    REQUIRED_ARG(           TAutoString,"!Key")

  EXPOSE_PROPRO(Window,    TCalcWindow,"!Window",      "@Window_", HC_TCALC_WI NDOW)

  EXPOSE_METHOD(LookAt,    TAutoLong,  "!LookAtWindow","@LookAtWindow_",

        HC_TCALC_LOOKATWINDOW)

    REQUIRED_ARG(           TCalcWindow,"!Window")

  EXPOSE_PROPRO(MyArray,   TMyArray,   "!Array",       "@Array_", HC_TCALC_ARRAY)

  EXPOSE_APPLICATION(      TCalc,      "!Application", "@Application_",

        HC_TCALC_APPLICATION)

END_AUTOCLASS(TCalc, tfNormal, "TCalc", "@TCalc", HC_TCALC)

The EXPOSE_xxxx macros assign names to methods and properties. EXPOSE_PROPRW defines a property that controllers can both read and write. EXPOSE_PROPRO limits a controller's access so it can only read the property value. REQUIRED_ARG assigns a name to a function argument.

For example, a controller invokes the server’s LookAt function by calling LookAtWindow and passing a Window parameter. The DEFINE_AUTOCLASS and END_AUTOCLASS macros assign "TCalc" as the public name for objects of type TCalc.

Most of the strings in this automation definition begin with a symbol, either ! or @. These symbols indicate that the AutoCalc application has in its resources translations for each public symbol. Each command from an automation controller comes with a locale ID indicating the language the controller is using. If the controller was written in German, for example, it can pass the string "Auswerten" instead of "Evaluate," and ObjectComponents correctly invokes the Eval function.

Every item listed in the automation definition must already appear in the automation declaration. For example, every function name you define with EXPOSE_METHOD must have a corresponding AUTOFUNC declaration. Every EXPOSE_PROP must have a corresponding AUTOPROP, AUTOFUNC, AUTOFLAG, or AUTODATA, depending on how you implement the property.

The parts of a definition macro

The macros for exposing methods and properties have five parameters: the internal name, the type of value returned, the external name, and a documentation string. The optional fifth parameter allows you to associate a Help context ID with each member.

MACRONAME(InternalName, ReturnType, ExternalName, DocString, HelpContext )

InternalName is the identifier string you assigned to the member in the automation declaration.

ReturnType tells what automation data type the method returns or the property holds.

ExternalName is what automation controllers see. A user sending commands from a controller refers to all properties and methods by their external names.

DocString should explain to a user what the exposed property or method does. OLE displays this string if the user asks for help with a particular automation command. If you omit the document string, set the parameter to 0.

HelpContext, the fifth parameter, is optional. It is a number that identifies a particular section of a Windows Help file (.HLP). You can create a Help file that describes the syntax and usage of all the members you expose. If you supply the context IDs for each member in the class's automation definition, then an automation controller can ask OLE to display the help screens for the user. A user writing an automation script, for example, can browse at run time for the list of members your application exposes, ask to see their document strings, and even ask to see a Help screen about each one.

If you provide a Help file for automation, you should be sure to register its name with the typehelp key.

When exposing a method that takes arguments, you also need to add a macro describing each argument to the definition. Here is the prototype for a function that takes three arguments, along with the macros needed to define the method for automation:

// member function declaration

long TCalculator::AddNumbers(short Num1, short Num2 = 0, short Num3 = 0);

// later, this appears after DEFINE_AUTOCLASS(TCalculator)

EXPOSE_METHOD(AddNumbers, TAutoLong, "AddNumbers", "Sum up to 3 numbers", HC_ADDNUMBERS)

  REQUIRED_ARG(TAutoShort, "Num1")

  OPTIONAL_ARG(TAutoShort, "Num2", "0")

  OPTIONAL_ARG(TAutoShort, "Num3", "0")

The first argument, Num1, is required. The others are optional. All three are short integers. When describing optional arguments, you need to supply a default value. In the example, 0 is the default value for the two optional arguments.

OLE conventions suggest that each automation object should have a property representing the application it belongs to. You can add this property to any automation definition with the EXPOSE_APPLICATION macro.

EXPOSE_APPLICATION(TMyClass, "Application", "My Application",)

The class passed to EXPOSE_APPLICATION must be the same class passed to the factory template.

Data type specifiers in an automation definition

Most of the macros in an automation definition ask for a data type of a function's return value, of each function argument, or of a data member. The possible values for data types within an automation definition are not fundamental C types. They can be any of the following:

An enumeration value previously defined for automation.

The name of an automated class (such as TCalc).

Any of the predefined classes that ObjectComponents provides to represent intrinsic C types.

The reason for exposing predefined classes rather than intrinsic C types is to make type information available when browsing from the controller. For exposed classes, ObjectComponents can extract type information using RTTI.

The automation data types are defined as structures that contain no data; they simply retrieve a static value indicating a data type. The identifier values are the same identifiers that OLE uses to distinguish the data types it supports. All the automation data types derive from a base called TAutoVal, so they are polymorphic. In effect, ObjectComponents can ask any value passed through automation to describe its own data type. For more information, see the table provided in Declarations and Definitions of Automation Data Types.


Compiling and linking an automation server
Step 6: Compiling and linking an automation server

See also

Automation servers and controllers can be compiled with any memory model except Small. (They run fastest in medium model.) And automation servers must be linked with the OLE and ObjectComponents libraries.

The IDE chooses the right build options for you when you ask for OLE support. To build any ObjectComponents program from the command line, create a short makefile that includes the OCFMAKE.GEN file found in the EXAMPLES subdirectory.

EXERES = MYPROGRAM

OBJEXE = winmain.obj myprogram.obj

!include $(BCEXAMPLEDIR)\ocfmake.gen

EXERES and OBJEXE hold the name of the file to build and the names of the object files to build it from. The last line includes the OCFMAKE.GEN file. Name your file MAKEFILE and type this at the command line prompt:

make MODEL=F, SYSTEM=WIN32

MAKE, using instructions in OCFMAKE.GEN, will build a new makefile tailored to your project. The new makefile is called WIN32Fxx.MAK.

Note:	The first time the server runs, the registrar object records its information in the registration database. Be sure to run the server once before trying to use it with a controller.


Exposing collections of objects

See also

ObjectComponents lets an automated object expose collections of various types as object properties. The items in a collection can belong to an array, a linked list, or any other structure that organizes sets of similar items.

To expose a collection, you need to expose methods for manipulating it. These methods typically include a counter to show the size of the collection, an iterator to walk through the collection, and a random-access function to retrieve specific items in the collection.

A collection object is an object that returns on request individual items from a set of related items. It implements the methods that manipulate the items. In the AutoCalc sample program, the buttons on the face of the calculator are a set of related, similar objects. AutoCalc defines a new class, TCalcButtons, whose methods let a controller ask for individual button objects. The buttons themselves are automated objects, so once a controller receives a button it can send a push command or change the text the button displays.

Constructing and exposing a collection class

If you are automating an existing application, you may find that it does not already have a C++ class to act as a collection object. The items might be simple values, structures, or even system objects represented by handles. You have to create a new C++ class, and you have to expose the class in the parent's automation tables as a property of the parent class.

How you expose the collection in the parent's automation declaration table depends on what information the parent passes the collection object to construct it. This section considers several different possible constructors and shows the macros for adding the collection as a property of its parent.

Instances of the collection class are constructed only when a controller requests it. The collection object appears to the controller as a property of the parent class. In AutoCalc, for example, when a controller asks for what is in the Buttons property, ObjectComponents creates a TCalcButtons object on the fly. The constructor of a collection object must accept a single argument passed from the parent to initialize itself.

Because TCalcButtons manages a collection of child windows, its parent passes the handle of the parent window. The constructor looks like this:

TCalcButtons(HWND window) : HWnd(window) {}

For the handle to be passed to the constructor, the parent must add a line to its automation declaration:

// from the automation declaration of the parent class

DECLARE_AUTOCLASS(TCalcWindow)

  AUTODATARO(Buttons, hWnd, TAutoObjectByVal<TCalcButtons>,)

Buttons is assigned as the internal name of a read-only property whose value is TCalcWindow::hWnd. For the data type of this property, the table specifies a new class based on the collection class. TAutoObjectByVal<T> causes an instance of T to be constructed that persists until all external references to that instance are released (when the exposed object goes out of scope in the automation controller).

TCalcWindow must also expose the collection property in its automation definition:

// from the automation definition of the parent class

DEFINE_AUTOCLASS(TCalcWindow)

  EXPOSE_PROPRO(Buttons, TCalcButtons, "!Buttons", "@Buttons_", HC_TCALCWINDOW_BUTTONS)

When a controller asks for what is stored in the read-only property called Buttons, ObjectComponents creates a TCalcButtons object and passes hWnd to its constructor.

Other ways to expose a collection object

Here are three examples showing other ways a parent class might expose a collection object as one of its properties:

Case 1: TParent::DocList points to the head of a linked list of TDocument objects. A new class, TDocumentList, is created as the collection object. The constructor of TDocumentList receives from its parent the head of the linked list:

TDocumentList(TDocument*);

The automation declaration of TParent exposes DocList as a read-only property, using the collection class to assign it a type.

DECLARE_AUTOCLASS(TParent)

  AUTODATARO(Documents, DocList, TAutoObjectByVal<TDocumentList>,)

The automation definition of TParent calls the collection Documents and says its type is TDocumentList.

DEFINE_AUTOCLASS(TParent)

  EXPOSE_PROPRO(Documents, TDocumentList, "Documents", "Doc Collection", 270)

Case 2: TParent contains a list. It passes this to the collection object, TList, which extracts list items by indirection through the parent's pointer. The constructor receives the pointer.

TList(TParent* owner)

The automation declaration of TParent exposes this as a read-only property, using the collection class to assign it a type.

DECLARE_AUTOCLASS(TParent)

  AUTOTHIS(List, TAutoObjectByVal<TList>,)

The automation definition of TParent calls the collection List and says its type is TList.

DEFINE_AUTOCLASS(TParent)

  EXPOSE_PROPRO(List, TList, "List", "List of items", 240)

Case 3: Elem is an array of integers, defined as short Elem[COUNT]. The collection object is TMyArray, and the constructor receives from the parent a pointer to Elem.

TMyArray(short* array)

The automation declaration of TParent exposes Elem as a read-only property, using the collection class to assign it a type.

DECLARE_AUTOCLASS(TParent)

  AUTODATARO(MyArray, Elem, TAutoObjectByVal<TMyArray>,)

The automation definition of TParent calls the collection Array and says its type is TMyArray.

DEFINE_AUTOCLASS(TParent)

  EXPOSE_PROPRO(MyArray, TMyArray, "Array", "Array as collection", 110)

Implementing an iterator for the collection

The collection class performs whatever actions you want a controller to be able to perform with the collection. Common collection methods include Count and GetObject, which return the number of items in the collection or individual items specified by number. The only methods you need to implement, however, are the constructor and an iterator. You have already seen the constructor. An iterator function walks through the collection and returns successive items on each new call.

The easy way to define an iterator is with the AUTOITERATOR macro, which you add to the declaration table of the collection object.

DECLARE_AUTOCLASS(TCalcButtons)

  AUTOITERATOR(int Id, Id = IDC_FIRSTID+1, Id <= IDC_LASTID, Id++,

               TAutoObjectByVal<TCalcButton>(::GetDlgItem(This->HWnd,Id)))

The parameters to AUTOITERATOR define the algorithm for enumerating objects in the collection. Each of the five macro arguments represents a code fragment, ordered as in a for loop.

1.	Declare state variables for keeping track of loop iterations. For example,

int Index;

2.	Assign initial values to the state variables. For example,

Index = 0;

3.	Test a Boolean expression to decide whether to enter the loop. For example,

Index < This->Total

4.	Modify state variables to prepare for the next iteration. For example,

Index++;

5.	Retrieve one item from the collection. For example,

(This->Array)[Index];

Note that the server can return any data type for items—values or objects.

In the AUTOITERATOR parameters, only use commas inside parentheses. Semicolons can separate multiple statements, but cannot be used to end a macro argument. As in automated methods, This is defined to be the this pointer of the enclosing C++ class (here, the collection itself).

AUTOITERATOR puts an iterator in the automation declaration table, but the iterator member must still be exposed in the definition table. Use the EXPOSE_ITERATOR macro.

EXPOSE_ITERATOR(TAutoShort, "Array Iterator", HC_ARRAY_ITERATOR)

EXPOSE_ITERATOR takes fewer parameters than other EXPOSE_xxxx macros do. No internal or external names are supplied. A class can have only one iterator, and the external name is always _NewEnum. The first parameter describes the type of the items returned from the iterator.

The automation type describes the type of the items returned from the iterator, in the same manner as a function return. The previous example iterates an array of short int values, so its automation data type is TAutoShort. The second parameter is the documentation string describing the iterator property, and the third parameter, which is optional, identifies a context in an .HLP file for more information about the iterator.

From the external side, a script controller sees the enumerator as a property with the reserved name _NewEnum that returns an object supporting the standard OLE interface IEnumVARIANT. This interface contains methods to perform iteration. A controller makes use of an iterator in a loop like this one, which is written in Visual Basic for Applications:

For Each Thing in Owner.Bunch  ("Thing" is an arbitrary iterator name)

  Thing.Member......           (can access methods and properties)

  Next Thing                   (loops through all items in collection)

The AUTOITERATOR macro generates a nested class definition within the collection class. For complex iterators, you can choose to code the iterator explicitly in C++. Here is an example:

class TIterator : public TAutoIterator {

  public:

    ThisClass* This;

    /* declare state variables here as members */

    void Init() {/* loop initialization function body */}

    bool Test() {/* loop entry test function body */}

    void Step() {/* loop iteration function body;}

    void Return(TAutoVal& v) {/* current element return: v = expr */}

    TIterator* Copy() {return new TIterator(*this);}

    TIterator(ThisClass* obj, TServedObject& owner)

                  : This(obj), TAutoIterator(owner) {}

    static TAutoIterator* Build(ObjectPtr obj, TServedObject& owner)

    { return new TIterator((ThisClass*)obj, owner); }

};

friend class TIterator;    // make iterator a friend of the surrounding collection class

Adding other members to the collection class

In addition to exposing an iterator, a collection class by convention exposes a Count method to return the number of items in the collection, an Index method for random access to members of the collection, and optionally, methods such as Add and Delete to manage the collection externally. Here, for example, is the complete code for the TCalcButtons collection class in AutoCalc:

class TCalcButtons {    // class used only temporarily to expose collection

  public:

    TCalcButtons(HWND window) : HWnd(window) {}

    short GetCount() { return IDC_LASTID - IDC_FIRSTID; }

    HWND GetButton(short i) {return ::GetDlgItem(HWnd, i + IDC_FIRSTID+1);}

    HWND HWnd;

  DECLARE_AUTOCLASS(TCalcButtons)

    AUTOFUNC0 (Count, GetCount, short,)

    AUTOFUNC1 (Item,  GetButton, TAutoObjectByVal<TCalcButton>, short,

                          AUTOVALIDATE(Arg1 >= 0 && Arg1 < This->GetCount()) )

    AUTOITERATOR(int Id, Id = IDC_FIRSTID+1, Id <= IDC_LASTID, Id++,

                 TAutoObjectByVal<TCalcButton>(::GetDlgItem(This->HWnd,Id)))

};

DEFINE_AUTOCLASS(TCalcButtons)

  EXPOSE_PROPRO(Count, TAutoLong, "!Count", "@CountBu_", HC_TCALCBUTTONS_COUNT)

  EXPOSE_ITERATOR(TCalcButton, "Button Iterator", HC_TCALCBUTTONS_ITERATOR)

  EXPOSE_METHOD_ID(0, Item, TCalcButton,"!Item",  "@ItemBu_", 0)

    REQUIRED_ARG(TAutoShort, "!Index")

END_AUTOCLASS(TCalcButtons, tfNormal, "TButtonList", "@TCalcButtons", HC_TCALCBUTTONS)


Exposing data for enumeration

See also

An automation server might also need to expose enumerated values. Use OLE enumerations when you want to expose a set of internal data values and refer to them with localizable strings. For example, AutoCalc defines the enumerated type operators to represent different actions the calculator can perform with numbers.

enum operators {

  OP_NONE = 0,

  OP_PLUS,

  OP_MINUS,

  OP_MULT,

  OP_DIV,

  OP_EQUALS,

  OP_CLEAR,

};

As the calculator receives input, it stores the pending mathematical operation in a private data member called Op.

short Op;

Operations are identified by different OP_xxxx constants. The Eval method performs the pending operation using the number just entered and the total in the calculator's accumulator. AutoCalc exposes the Op data member to automation so that a controller can enter operators directly. Here's the automation declaration:

AUTODATA(Op, Op, short, AUTOVALIDATE(Val>=OP_NONE && Val<=OP_CLEAR))

The automation declaration shows that the Op data member holds a short value, but the symbols OP_PLUS and OP_MINUS are defined only within the server program. The controller can't use them when it passes commands. Ideally the controller should be able to use more readable strings such as "Add" and "Subtract" in scripts.

The place for declaring public symbols is the automation definition. Use the DEFINE_AUTOENUM macro to begin a table defining symbols for the enumerated values.

DEFINE_AUTOENUM(CalcOps, TAutoShort)

  AUTOENUM("Add",      OP_PLUS)

  AUTOENUM("Subtract", OP_MINUS)

  AUTOENUM("Multiply", OP_MULT)

  AUTOENUM("Divide",   OP_DIV)

  AUTOENUM("Equals",   OP_EQUALS)

  AUTOENUM("Clear",    OP_CLEAR)

END_AUTOENUM(CalcOps, TAutoShort)

The AUTOENUM macro takes two parameters: an enumeration string and a constant value. The enumeration string (which can be localized) is the external name exposed through OLE for use by controllers.

The macros that begin and end the enumeration table assign the name CalcOps to this enumerated type. They also associate the automated data type TAutoShort with this enumeration because the enumerated values are all short ints.

The following table lists the C++ types that can be enumerated and the corresponding automation types for exposing them.

C++ type	Enumeration type (for automation definitions)

bool	TAutoBool

double	TAutoDoubl

float	TAutoFloat

int	TAutoInt

long	TAutoLong

short	TAutoShort

const char*	TAutoString

Creating a table of enumerated values results in a new data type that you can use to describe arguments and return values in an automation definition. Now that ObjectComponents understands the CalcOps enumerated type, you can use the type to define the Op property.

EXPOSE_PROPRW(Op, CalcOps, "Op", "@Op_", HC_TCALC_OPERATOR)

This line says that Op is a read-write property holding a value of type CalcOps. When the controller tries to place "Multiply" or "Divide" in the Ops property, ObjectComponents correctly translates the string into the value defined as OP_MULT or OP_DIV.


Combining multiple C++ objects into a single OLE automation object

See also

The complete set of member functions and properties that belong to a single automated OLE object can in fact be implemented by a combination of C++ objects. An automated calendar, for example, might begin with a TCalendar class. But the automated OLE calendar object might need to expose some methods and properties that don't happen to belong to the C++ TCalendar object.

For example, the background color might be inherited from TCalendar's base class, and some of the input functions might belong to separate control windows in the calendar's client area. In that case, the automation declaration for TCalendar should delegate some tasks to other C++ classes.

To combine several C++ objects together into a single OLE object, add macros to the automation definition table.

// these lines belong in the definition block that begins DEFINE_AUTOCLASS(TCalendar)

    EXPOSE_INHERIT(TCalendarWindow, "CalendarWindow")

    EXPOSE_DELEGATE(TWeekForwardButton, "WeekForward",

      GetWeekForwardButton(this))

Any exposed classes must also be automated. In other words, TCalendarWindow and TWeekForwardButton must also have their own AUTOCLASS tables. By exposing both of these classes in the TCalendar automation definition, you combine all the exposed members from all three classes into a single symbol table. When OLE sends an automation command to the calendar, ObjectComponents searches for the matching class member in TCalendar, then in TCalendarWindow, and finally in TWeekForwardButton.

The EXPOSE_DELEGATE macro takes as its third parameter a conversion function. To reach members in the delegation class, ObjectComponents needs a pointer to an object of that class. The conversion function has one parameter for receiving a this pointer to the object where the definition table appears. The function must return a pointer to the delegation object. Also, it must be a global function. For example, if TCalendar has a data member that points to the Week Forward button, this might be the conversion function.

TWeekForwardButton *GetWeekForwardButton ( TCalendar* this ) {

  return( this->m_ForwardButton );

}

You don't need to provide a conversion function when exposing an inherited function or property because in that case ObjectComponents can create its own templatized conversion function to reach the base class.

Another way to coordinate the actions of several automated objects within a single application is to give one object access functions that return the other objects.

For example, the sample program AutoCalc automates five different classes, but no class delegates to any other. When a controller asks for an object from the AutoCalc server, it receives only the automated TCalc object. TCalc, however, has a property called Window that holds a TCalcWindow object. TCalcWindow, in turn, has a property that holds the collection of buttons. The collection object returns individual button objects. Without properties or functions that return the other objects, the controller would never be able to reach them. Be sure to add access functions if necessary.


Telling OLE when the object goes away

See also

If there is a chance that your program might delete its automated object while still connected to a controller, then you need to tell OLE when the object is destroyed. This precaution only matters if the logic of your program might cause the object to be destroyed through nonautomated means while an OLE session is still in progress. If OLE attempts to use an automation object whose underlying C++ object has been destroyed, it attempts to use an invalid pointer. A single function call prevents the error by sending OLE an obituary to announce that the object no longer exists.

// place this line in the destructor of your automated class

::GetAppDescriptor()->InvalidateObject(this);

GetAppDescriptor is a global function returning a pointer the application's TAppDescriptor object. InvalidateObject is a TAppDescriptor method. It tells OLE the object that was passed to the descriptor's InvalidateObject function is now invalid.

Although the object's destructor is a good place to call InvalidateObject, you can call it anywhere. If you do not own the class you are automating, it might not be possible to modify the destructor. This works, too:

TMyAutoClass* MyAutomatedObject = new TMyAutoClass;

.

.

.

::GetAppDescriptor()->InvalidateObject(MyAutomatedObject);

delete MyAutomatedObject;

The object pointer you pass to InvalidateObject must always represent the most derived form of the object. In other words, if the pointer is polymorphic, it must point to the class as it was created and not to any of its base classes. Calling InvalidateObject from the object's own destructor is safe because in that case this always points to the most derived class. If you call InvalidateObject from somewhere else, you might need the global function MostDerived to ensure that you are invalidating the correct object.

appDesc->InvalidateObject(::MostDerived(MyPolymorphObject, typeid(MyPolymorphObject)));

In the example, MyPolymorphObject is a pointer to a polymorphic object, so it might point to a base class or to an object of any type derived from the base. MostDerived converts the pointer, making it point to an object of the type farthest down the hierarchy, the one furthest descended from the base.

Besides calling InvalidateObject, there are two other ways let OLE know when the object is destroyed. One way is to derive the object's class from TAutoBase. The only code in TAutoBase is a virtual destructor that calls InvalidateObject for you. This example declares a class called TMyAutoClass. OLE always knows when any object of type TMyAutoClass is destroyed.

class TMyAutoClass: public TAutoBase { /* declarations */ };

The other way is to put the AUTODETACH macro in the class's automation declaration table. This works without having to change the class derivation, but it does add one byte to the size of the class.


Localizing symbol names

See also

The symbols that appear in an automation definition become visible to other OLE programs. Users writing scripts can see and use the symbols. The symbols become part of the program's user interface. Programs intended for international audiences need to translate the strings for different markets. For example, a property named "Color" in English should be called "Couleur" in a French script, "Farbe" in a German script, and "Colour" in a British one.

The external names in macros like EXPOSE_METHOD and EXPOSE_PROPRW are wrapped in objects of type TLocaleString, a localizable substitute for char* strings. A TLocaleString object contains code that searches a program's executable file for XLAT resources. All access to the XLAT resources is performed by TLocaleString.

The TLocaleString class is defined in winsys/lclstrng.h. You don't need to refer to TLocaleString directly. The macros and headers bring it in for you.

TLocaleString is very efficient. If the controller is working in the server's native language, then TLocaleString realizes the strings in the source code already match the locale and it doesn't waste any time reading resources.

Usually ObjectComponents determines the application's default language by reading the system's locale ID at compile time and storing it in the compiled program. You can override the default by including a line like this in your source code.

#include "winnls.h"  // include olenls.h for 16-bit applications

TLangId TLocaleString::NativeLangId=MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US);

The olenls.h header holds national language support constants, including the MAKELANGID macro and the language and dialect symbols.

When it must resort to resources, TLocaleString does everything it can to minimize the time spent searching for translations. When it finds a string to match the current locale, it caches the string in memory and never has to load it again. That means only the first attempt to use each translated string incurs a performance hit. Subsequent requests are satisfied quickly. Once in memory, the strings are stored in a hash table so no space is wasted on duplicates. If TLocaleString fails to find a requested string, it remembers the failure as well and won't try to find the same string a second time.

The same localization mechanism works with strings your application registers. Some strings, such as the progid, should not be localized, but you can localize the following registration keys:

appname

debugdesc

description

formatn

menuname

permname

typehelp

verbn

The following excerpt from the AutoCalc registration tables shows where to put the localization prefixes. The appname, description, and typehelp keys are localized.

BEGIN_REGISTRATION(AppReg)

  REGDATA(clsid,      "{877B6200-7627-101B-B87C-0000C057CE4E}")

  REGDATA(progid,     APP_NAME ".Application")

  REGDATA(appname,    "@AppName")

  REGDATA(description,"@Desc")

  REGDATA(typehelp,   "@typehelp")

  REGDATA(version,    "1.2")

END_REGISTRATION

AutoCalc supplies translations for the appname, description, and typehelp strings in its resource script. Here are two of them.

Desc         XLAT "Automated Calculator 1.2 Application"

           GERMAN "Automatisierte Taschenrechner-Anwendung 1.2"

             XEND

Typehelp     XLAT "autocalc.hlp"

           GERMAN "acalcger.hlp"

             XEND

ObjectComponents determines the proper language for registration by examining the system settings at run time, but it is possible to override the system setting with the Language command-line switch.

OLE does its best to help you out by passing a number that indicates the user's language setting. This number is called a locale ID, or LCID. LCIDs are defined by OLE and the Win32 API. They consist of two numbers, one identifying a language and one identifying a subdialect within the language. When OLE passes an automation call into an automated application, it also passes an LCID. The automation controller might determine the LCID from the system settings at run time, or the person using the controller might choose a locale.

An automated program is expected to examine the LCID and respond with appropriately translated strings. ObjectComponents eases the burden by letting you build a resource table to supply localized versions of any strings you use. When handling automation calls, ObjectComponents automatically searches the table to find strings that match whatever language the controller requests.

ObjectComponents searches first for a string with the correct language and dialect IDs. Failing that, ObjectComponents searches for a match on primary language only, ignoring dialect. If still no match is found, ObjectComponents simply uses the original, untranslated string.

Putting translations in the resource script

To build a table of translations in your resource (.RC) file, use the XLAT resource type.

#include "owl/locale.rh"

Left    XLAT FRENCH "Gauche" GERMAN "Links" SPANISH "Izquierda" XEND

Right   XLAT FRENCH "Droit"  GERMAN DUTCH "Rechts"              XEND

Center  XLAT ENGLISH_UK FRENCH GERMAN "Centre" SPANISH "Centro" XEND

Help    XLAT FRENCH "Aide" GERMAN "Hilfe" SPANISH "Ayuda"       XEND

The locale.rh header file defines XLAT as a type of resource. XLAT and XEND are delimiters for all the translations of a single string. The same header also defines macros to represent various locale IDs. FRENCH, DUTCH, and ENGLISH_UK, for example, each represent a different LCID. UK is a subdialect of ENGLISH.

Each line in the localization table begins with a resource identifier. These examples use the original string itself to identify the resource that holds its translations.

A localization table is not obliged to provide the same set of translations for each string. For example, it is legal to provide FRENCH_FRANCE, FRENCH_BELGIUM, and SWEDISH for one string, but only FRENCH and ITALIAN for the next string. Also, if several languages use the same string, it is legal to write the string only once, as in this example:

Center XLAT ENGLISH_UK FRENCH GERMAN "Centre" SPANISH "Centro" XEND

In British English, French, and German, "Center" is translated as "Centre." in Spanish, it becomes "Centro." Writing "Centre" only once keeps the .EXE file smaller.

Marking translatable strings in the source code

Composing a resource table is the first step, but ObjectComponents still needs to be told when to use the table you have provided. In the automation definition, mark each translatable string by prefixing it with an exclamation point.

EXPOSE_METHOD(Clear, TAutoVoid, "!Clear", "Clear accumulator", HC_TCALC_CLEAR)

This line from AutoCalc exposes a class method named Clear. Clear returns void. The third parameter, !Clear, gives the external name that controllers see. The initial exclamation point tells ObjectComponents to look in the program's executable file for a localization resource whose identifier is the string Clear.

Clear XLAT GERMAN "AllesLöschen" XEND

The exclamation point prefix also marks Clear as the language-neutral form of the string. If an automation controller decides to use the locale ID GERMAN, then ObjectComponents tells it that the exposed property is called AllesLöschen. If the controller sets any other locale ID, it receives the neutral form, Clear.

Argument names as well as properties and methods can be localized.

EXPOSE_METHOD(Button, TAutoBool, "!Button", "Button push sequence", HC_TCALC_BUTTON)

   REQUIRED_ARG( TAutoString, "!Key")

in determining what to call both the Button method and its one argument, ObjectComponents will search the program's localization resources for Button and Key.

Button       XLAT GERMAN "Schaltfläche" XEND

Key          XLAT GERMAN "Taste" XEND

The algorithm that searches for resources is not sensitive to case.  Under 16-bit Windows, the algorithm does not allow the use of extended characters (such as characters with diacritical marks) in resource names. However, the strings stored in a resource can use any characters and do preserve their case.

A problem arises in naming your resource if the string contains spaces. Resource identifier strings cannot have spaces. Consider what happens if you try to localize the description string for this property:

// illegal: no spaces allowed in resource identifiers

EXPOSE_PROPRW(Caption, TAutoString, "!Caption", "!Window Title", HC_TCALCWINDOW_TITLE)

It's a good idea to localize descriptions as well as property names, but "Window title" is not a legal resource identifier. In cases like this, use @ instead of ! as the localization prefix, and follow it with any legal identifier.

EXPOSE_PROPRW(Caption, TAutoString, "!Caption", "@Caption_",HC_TCALCWINDOW_TITLE)

The @ prefix tells ObjectComponents that the string is only a resource identifier and should never be displayed no matter what locale the controller requests. To make the distinction even clearer for programmers reading the code, strings used only as identifiers conventionally end with an underscore, as in Caption.

To make "Window Title" the language-neutral string, do not assign it a locale ID in the localization resource.

Caption_ XLAT "Window Title" GERMAN "Fenster-Aufschrift" XEND

Now a controller that requests any locale setting other than GERMAN is given the string Window Title.

Besides ! and @, there is a third localization prefix: #. The # prefix must be followed by digits that identify a localization resource by number.

EXPOSE_PROPRW(Caption, TAutoString, "!Caption", "#10047",HC_TCALCWINDOW_TITLE)

This example tells ObjectComponents to look for a resource numbered 10047. This is how the resource should appear in the .RC file:

10047 XLAT "Window Title" GERMAN "Fenster-Aufschrift" XEND


Creating a type library

See also

A type library is a binary file containing information about an automation server. The information describes the objects, properties, and methods the server supports. It is used by programming tools, such as automation controllers, that call the server. Controllers can query the type library for documentation and help with specific objects. The location of its type library is one of the pieces of information an automation server records in the system's registration database.

ObjectComponents can create a type library for you from information in the server's automation definitions. To make a type library, call the server and set the -TypeLib switch on the command line.

myapp -TypeLib

This command causes ObjectComponents to create a new file, MYAPP.OLB, in the same directory as MYAPP.EXE. ObjectComponents also records the library's location in the registration database.

The -TypeLib flag also accepts an optional path and file name.

myapp -TypeLib = data\mytyplib

ObjectComponents places MYTYPLIB.OLB in a subdirectory called DATA under the directory where MYAPP.EXE resides.

You can also make ObjectComponents generate multiple type libraries in different languages with the -Language switch. This command produces two type libraries, one in German and one in Italian.

myapp -Language=10 -TypeLib=italiano -Language=7 -TypeLib=deutsch

The number passed to -Language must be hexadecimal digits. The Win32 API defines 80C as the locale ID for the Belgian dialect of the French language. For this command line to have the effect you want, myapp must supply Belgian French strings in its XLAT resources.

If you have a Help file, be sure to register it using the typehelp and helpdir registration keys. Use the final parameter of the EXPOSE_xxxx macros in the automation definition table to associate Help context IDs with each command. If the automation controller asks for help on a command, OLE launches the Help file automatically.


Turning an application into an OLE automation controller (OCF)
Turning an application into an OLE automation controller

See also

Follow these steps to turn an application into an OLE automation controller using OCF.

1. Include OCF header files.

2. Create a memory allocator object.

3. Declare proxy classes.

4. Implement proxy classes.

5. Create and use proxy objects.

6. Compile and link the application.

Note:	In order to send commands to an OLE object, the automation controller must know the names of methods and properties the object's server exposes to OLE. Generally these names come from the server's type library. The controller uses the names in creating C++ proxy classes whose methods send commands to the server. It's possible to browse through available automation objects at run time and discover what commands they support, but to make use of commands discovered at run time usually requires a scripting language.


Including OCF header files (automation controller)
Step 1: Including OCF header files (automation controller)

See also

An automation controller must include the following header files:

#include <ocf/autodefs.h>

#include <ocf/automacr.h>

The autodefs.h file defines automation classes such as TAutoProxy; the automacr.h file defines the macros a controller uses to implement proxy class methods.


Creating a memory allocator object (automation controller)
Step 2: Creating a memory allocator object (automation controller)

Automation controllers must create a memory allocator (TOleAllocator) object to initialize the OLE libraries. To create a TOleAllocator object, add this line to your program.

TOleAllocator OleAlloc(0);

Note: To initialize the OLE libraries under Win32, you must pass a zero argument to the TOleAllocator constructor. Under 16-bit Windows, you can also pass a pointer to a custom memory allocation function.

The constructor for TOleAllocator initializes the OLE libraries and its destructor releases them. Create an object of type TOleAllocator before you begin OLE operations and be sure the object is not destroyed until all OLE operations have ended. A good place to create the TOleAllocator is at the beginning of WinMain or OwlMain.


Declaring proxy classes
Step 3: Declaring proxy classes

See also

A proxy class is a C++ stand-in for an automated OLE object. You create a proxy class whose interface corresponds to that of the OLE object. By deriving the proxy class from TAutoProxy, you connect it to ObjectComponents. When a TAutoProxy object is constructed, it calls an OLE API to request the IDispatch interface of the automated object that the proxy represents. When you call a function of the proxy class, the proxy sends the corresponding command to the automation server.

An automation controller declares one proxy class for every type of object it wants to control. In simple cases, a single proxy class might be enough. Controlling a complex application that creates several different kinds of automatable objects requires more proxies. To control a spreadsheet, for example, you might need a proxy application class, a proxy spreadsheet class, and a proxy cell class.

The easiest way to declare and implement proxy classes is with the AutoGen utility. AutoGen reads the server's type library and generates C++ source code for the proxy classes a controller needs to send any commands to the server. Simply compile the generated code into your application, construct proxy objects when you need them, and call their member functions to send commands.

As an example of a proxy class, here is the code that AutoGen generates for the automated class TCalc in the AutoCalc sample program. The opening comment shows descriptive information from AutoCalc's entries in the registration database including the value of AutoCalc's version, clsid, and description registration keys. The comments for individual members show the documentation strings that AutoCalc assigns to each member in its automation definition table, the dispatch ID that ObjectComponents assigned to identify each command, and whether the member is a function or a property.

// TKIND_DISPATCH: TCalc 1.2 {877B6207-7627-101B-B87C-0000C057CE4E}\409

// Automated Calculator Class

class TCalc : public TAutoProxy {

  public:

    TCalc() : TAutoProxy(0x409) {}

    // Pending operand

    long GetOperand();     // [id(1), prop r/w]

    void SetOperand(long); // [id(1), prop r/w]

    // Calculator accumulator

    long GetAccumulator();     // [id(0), prop r/w]

    void SetAccumulator(long); // [id(0), prop r/w]

    // Pending operation

    TAutoString GetOp();     // [id(3), prop r/w]

    void SetOp(TAutoString); // [id(3), prop r/w]

    // Evaluate operand, op

    TBool Evaluate(); // [id(4), method]

    // Clear accumulator

    void Clear(); // [id(5), method]

    // Update display

    void Display(); // [id(6), method]

    // Terminate calculator

    void Quit(); // [id(7), method]

    // Button push sequence

    TBool Button(TAutoString Key); // [id(8), method]

    // Calculator window

    void GetWindow(TCalcWindow&); // [id(9), propget]

    // Test of object as arg

    long LookAtWindow(TCalcWindow& Window); // [id(10), method]

    // Array as collection

    void GetArray(TCalcArray&); // [id(11), propget]

    // Application object

    void GetApplication(TCalc&); // [id(12), propget]

};

The constructor of an automation proxy class must pass to its base class, TAutoProxy, a number representing a locale setting. The locale tells what language the automation controller uses when it sends commands to objects. in the example, the number is 0x409, which is the locale ID for American English. AutoGen chooses this locale by reading the system settings when it runs, but you are free to change it to whatever locale you prefer.

The function members of class TCalc each send a different command to the calculator object. Read-write properties get two commands, one for getting the value and one for setting it. GetOp and SetOp, for example, write and read the value representing the next operation the calculator will perform. Other commands, such as Display and Quit, make the calculator perform some action.


Implementing proxy classes
Step 4: Implementing proxy classes

See also

After declaring methods, you implement them. Each method must send a command through ObjectComponents to the automated object. Here is part of the implementation code that AutoGen generates for the TCalc proxy object. Every method simply calls the same three macros.

// TKIND_DISPATCH: TCalc 1.2 {877B6207-7627-101B-B87C-0000C057CE4E}\409 Automated Calculator Class

TAutoString TCalc::GetOp()

{

  AUTONAMES0("Op")

  AUTOARGS0()

  AUTOCALL_PROP_GET

}

void TCalc::SetOp(TAutoString val)

{

  AUTONAMES0("Op")

  AUTOARGS0()

  AUTOCALL_PROP_SET(val)

}

TBool TCalc::Evaluate()

{

  AUTONAMES0("Evaluate")

  AUTOARGS0()

  AUTOCALL_METHOD_RET

}

void TCalc::Clear()

{

  AUTONAMES0("Clear")

  AUTOARGS0()

  AUTOCALL_METHOD_VOID

}

void TCalc::Display()

{

  AUTONAMES0("Display")

  AUTOARGS0()

  AUTOCALL_METHOD_VOID

}

void TCalc::Quit()

{

  AUTONAMES0("Quit")

  AUTOARGS0()

  AUTOCALL_METHOD_VOID

}

void TCalc::GetWindow(TCalcWindow& obj)

{

  AUTONAMES0("Window")

  AUTOARGS0()

  AUTOCALL_PROP_REF(obj)

}

The three macros supply all the code needed for each function. The first two macros, AUTONAMES and AUTOARGS, specify what arguments you want to pass. They are explained in the following table. None of the methods in the example takes any arguments. The AUTOCALL_xxxx macros tell whether the command is a function or a property and what kind of value it returns.

Macro	Description

AUTOCALL_METHODn(id, arg...)	Calls a method with n arguments that returns a value.

AUTOCALL_METHODnV(id, arg...)	Calls a method with n arguments that returns void.

AUTOCALL_METHODn_REF(id, prx, arg...)	Calls a method with n arguments that returns a proxy object.

AUTOCALL_PROPGET(id)	Retrieves the value of a property.

AUTOCALL_PROPSET(id, arg)	Assigns a value to a property.

AUTOCALL_PROPREF(id, obj)	Retrieves the value of a property that contains an object. (Objects must be passed by reference.)

Specifying arguments in a proxy method

The first two macros in the implementation of a proxy method indicate what arguments you intend to pass. The server can decide that some arguments to a method are optional. You must pass all required arguments, and you can choose to pass any of the optional arguments.

For example, a server might expose a method that takes ten arguments, of which five are optional. Optional arguments have default values. Your controller might only need one of the optional arguments, always using the default values for the other four. In that case, you can set up your proxy implementation so that you have to pass only six arguments instead of ten.

The AUTONAMES macro lists the optional arguments that you want to use. It lists them by the names the server assigns to them. (AutoGen reads the names from the server's type library for you.)

The first argument passed to an AUTONAMES macro always identifies the automation method that this proxy command invokes. The names of arguments come after. If the automation server uses ObjectComponents, then the names used in AUTONAMES come from the server's automation definition table. The function name is the external name in an EXPOSE_METHOD macro, and the argument names come from subsequent OPTIONAL_ARG macros.

The second parameter in a proxy method implementation, AUTOARGS, lists all the arguments that the controller chooses to pass for this command. It tells what will be pushed onto the command stack. AUTOARGS must always list all the required arguments in order first. At the end of the list are any optional arguments from the AUTONAMES macro. If five arguments are required and the controller wants to pass only one of five optional arguments, then the list in AUTOARGS includes six arguments, the optional one last.

The names used for required arguments are just dummy names. Their position in the list indicates which argument they represent. The names for optional arguments must be the same as the names used in AUTONAMES. For optional arguments, the name itself is what identifies a particular parameter.

Note:	When an automation command passes an object as a parameter or a return value, be sure to pass by reference, not by value. For example, access functions for a property implemented as an object should follow this form:

GetObjectX( X& obj );

SetObjectX( X& obj );

Passing objects by assignment makes it impossible to provide C++ type safety.


Creating and using proxy objects
Step 5: Creating and using proxy objects

See also

Through a proxy class you can talk to an OLE object, but first the object has to exist. The TAutoProxy class defines a member function called Bind that asks OLE to create an object. The parameter passed to Bind determines the type of object to create. The most convenient identifier is usually a name the automation object has recorded in the registration database. (The object's unique clsid number also works but is harder to remember and write.) This is what an automation controller does to make OLE create a calculator object:

TCalc calc;                            // create proxy object

calculator.Bind("Calc.Application");   // make OLE create real object

The string passed to Bind is what the automation server registered as its progid:

REGDATA(progid, "Calc.Application")    // from server's registration table

The destructor for TAutoProxy calls the Unbind method, so when calculator goes out of scope, the calculator object is destroyed.

While calc remains in scope, the controller program issues commands by calling methods on the proxy object. The commands in the following example add 1234 + 4321 and display the result in the calculator's window.

calc.SetOperand(1234);

calc.SetOp("Add");

calc.Evaluate();

calc.SetOperand(4321);

calc.Button("+");

calc.Evaluate();

calc.Display();


Compiling and linking an automation controller
Step 6: Compiling and linking an automation controller

Automation servers and can be compiled with any memory model except Small. (They run faster in medium model.) And they must be linked with the OLE and ObjectComponents libraries.

The integrated development environment (IDE) chooses the right build options for you when you ask for OLE support. To build any ObjectComponents program from the command line, create a short makefile that includes the OCFMAKE.GEN file found in the EXAMPLES subdirectory.

EXERES = MYPROGRAM

OBJEXE = winmain.obj myprogram.obj

!include $(BCEXAMPLEDIR)\ocfmake.gen

EXERES and OBEXE hold the name of the file to build and the names of the object files to build it from. The last line includes the OCFMAKE.GEN file. Name your file MAKEFILE and type this at the command line prompt:

make MODEL=F, SYSTEM=WIN32

MAKE, using instructions in OCFMAKE.GEN, will build a new makefile tailored to your project. The new makefile is called WIN32Fxx.MAK.


Enumerating automated collections

Many automated objects have properties that represent a set of related items—for example, integers in an array, structures in a linked list, or a group of objects such as the buttons on the face of the calculator. To expose a collection, the automation server must implement a collection object with access functions. As OLE sees it, a collection object implements the standard IEnumVARIANT interface.

The following topics explain what a controller must do to use a collection object and enumerate items in the server:

1.	Declare a proxy collection class

2.	Implement the proxy collection class

3.	Declare a collection property

4.	Send commands to the collection

Declaring a proxy collection class

A proxy collection class usually supplies member functions to find out how many items are in the collection, to retrieve individual items randomly by their position in the list, and to enumerate the items in the list sequentially. (on the server's side, ObjectComponents calls this iterating. The controller uses the server's iterator to enumerate the items.)

Here is the proxy class that AutoGen creates to enumerate the collection of calculator buttons in AutoCalc.

// TKIND_DISPATCH: TButtonList 1.2 {877B6204-7627-101B-B87C-0000C057CE4E}\409

// Button Collection

class TButtonList : public TAutoProxy {

  public:

    TButtonList() : TAutoProxy(0x409) {}

    // Button Count

    long GetCount(); // [id(1), propget]

    // Button Iterator

    void Enumerate(TAutoEnumerator<TCalcButton>&); // [id(-4), propget]

    // Button Collection Item

    void Item(TCalcButton&, short Index); // [id(0), method]

};

The only thing here that wasn't in the previous proxy classes is the use of the TAutoEnumerator template. TAutoEnumerator encapsulates the code for manipulating the IEnumVARIANT interface of a collection object. The type you pass to the template is the type of value the collection contains. In the example, TCalcButton is another proxy class representing an automated button object in the server.

Implementing the proxy collection class

This is the code that AutoGen writes to implement the proxy collection class. Count and Item are straightforward. The Enumerate method does several new things, however.

// TKIND_DISPATCH: TButtonList 1.2 {877B6204-7627-101B-B87C-0000C057CE4E}\409 Button Collection

long TButtonList::GetCount()

{

  AUTONAMES0("Count")

  AUTOARGS0()

  AUTOCALL_PROP_GET

}

void TButtonList::Enumerate(TAutoEnumerator<TCalcButton>& obj)

{

  AUTONAMES0(DISPID_NEWENUM)

  AUTOARGS0()

  AUTOCALL_PROP_REF(obj)

}

void TButtonList::Item(TCalcButton& obj, short Index)

{

  AUTONAMES0("Item")

  AUTOARGS1(Index)

  AUTOCALL_METHOD_REF(obj)

}

First, the parameter to the Enumerate method is a reference to an object of the type that the collection contains. On successive calls, Enumerate returns collection items through this parameter. The data type for the parameter must use the TAutoEnumerator template.

Second, the method is identified to AUTONAMES0 as DISPID_NEWENUM. This is a predefined constant from oleauto.h representing the standard dispatch ID (which happens to be –4) for an enumerating command. The AUTONAMES0 macro accepts a dispatch ID instead of a function name. (The other AUTONAMES macros, those that expect argument names as well, require a name string for the function.)

Finally, an enumerator is a property of its object and it passes an object by value; so the enumerator implementation ends with the AUTOCALL_PROP_REF macro.

Declaring a collection property

TButtonsList is now fully defined as a proxy class for the server's collection object. What's needed now is a way to ask the controller for the collection. In AutoCalc, the collection of buttons is a property of the calculator's automated window object.

class TCalcWindow : public TAutoProxy {

  public:

    TCalcWindow() : TAutoProxy(0x409) {}

    // Button Collection

    void GetButtons(TButtonList&); // [id(5), propget]

The window class exposes the collection through a GetButtons command that returns the value of the collection property. GetButtons needs the TButtonList class to declare its parameter type.

Sending commands to the collection

This code from the sample program CallCalc sends the calculator commands that press its buttons. in the code, window is the automated window object. TCalcButton is the proxy class for individual buttons. TButtonList is the proxy object for the collection.

TButtonList buttons;                     // declare a collection object

window.GetButtons(buttons);              // bind buttons to automated collection object

TAutoEnumerator<TCalcButton> list;       // create an enumerator of TCalcButton objects

buttons.Enumerate(list);                 // bind list to the server's iterator

TCalcButton button;                      // declare a button object

for (i = IDC_FIRSTBUTTON;; i++) {

  list.Object(button);                   // bind button to an automated button object

  button.SetActivate(true);              // press the calculator button

  list.Step()// list.Step advances to the next item in list

}

The buttons, list, and button variables are each created in one step and then bound to a server object in another. Each of them is a proxy object for something the server created; buttons, for example, is the proxy object for a collection of automated button objects. Simply declaring a proxy object, however, does not attach it to any particular automated object in the server.

To be able to send commands, a proxy object must be bound to something with an automation interface (IDispatch or IEnumVARIANT). Because the server defines the collection of buttons as a property of the calculator's window, this command retrieves the collection and connects it to the buttons proxy object:

window.GetButtons(buttons);  // bind buttons to automated collection object

The two other lines where the comments indicate binding takes place similarly connect list to the collection's iterator object and button to individual button objects in the collection.

A simple assignment statement might seem more intuitive than the binding step, but the only value that could be assigned in these cases is simply a pointer to an automation interface. A pointer carries no type information; a pointer to a collection's IDispatch looks just like the pointer to a button's IDispatch. Binding to an existing C++ object preserves information about what kind of automation object it represents.


Turning an application into an OCX container or an OLE container using ObjectComponents

See also

Follow these steps to turn an application into an OCX container or an OLE container using ObjectComponents:

1. Include ObjectComponents header files.

2. Create an OLE memory allocator object.

3. Create OLE registration tables.

4. Connect an ObjectComponents application object to the main window.

5. Connect an ObjectComponents view object to the view window.

6. Handle OLE messages.

7. Handle OLE menu commands.

8. Create an ObjectComponents registrar object.

9. Compile and link the application.

Note: If you’re creating a new application, consider using AppExpert to save some work.

The topics that follow use code from the examples in the EXAMPLES/OCF/CPPOCF directory:

Example	Description

CPPOCF0	A basic windows application.

CPPOCF1	The CPPOCF0 example turned into a basic OLE container that registers itself in the system’s registration database, creates objects to initialize a new document, and allows standard OLE objects to be embedded.

CPPOCF2	The CPPOCF1 example turned into a basic OLE server.


Including ObjectComponents header files (container)
Step 1: Including ObjectComponents header files (container)

See also

An OCX container must include the following ObjectComponents header files:

#include <ocf/ocapp.h>       // TOcRegistrar, TOcModule, TOcApp

#include <ocf/ocdoc.h>       // TOcDocument

#include <ocf/occtrl.h>      // TOcxView and TOcControl

#include <ocf/ocfevx.h>      // WM_OCEVENT message crackers

An OLE container must include the following ObjectComponents header files:

#include <ocf/ocapp.h>       // TOcRegistrar, TOcModule, TOcApp

#include <ocf/ocdoc.h>       // TOcDocument

#include <ocf/ocview.h>      // TOcView

#include <ocf/ocpart.h>      // TOcPart

#include <ocf/ocfevx.h>      // WM_OCEVENT message crackers


Creating an OLE memory allocator object (container)
Step 2: Creating an OLE memory allocator object (container)

An OLE application should create an OLE memory allocator (TOleAllocator) object to initialize the OLE libraries. To create a TOleAllocator object, add this line to the application’s WinMain function.

TOleAllocator OleAlloc(0);


Creating an OLE registration table (container)
Step 3: Creating OLE registration tables (container)

Like any other OLE application, a container must register information about itself in the system’s registration database. Registration is performed automatically by ObjectComponents if you create a registration table for the application and each of its document types, and then pass the resulting structures to a registrar object. (You will learn more about the registrar object later.)

To create a registration table, use the BEGIN_REGISTRATION macro.

This is the application registration table used in the CPPOCF1.CPP example:

BEGIN_REGISTRATION(AppReg)

  REGDATA(clsid,        "{8646DB80-94E5-101B-B01F-00608CC04F66}")

  REGDATA(appname,      "Container")

END_REGISTRATION

Note: For a container, you must specify the class id and appname keys in the application registration table; and you must specify the progid, description, and formatn keys in the document registration tables. For more information, see the Registration Keys topic.


Binding an ObjectComponents application object to the main window (container)
Step 4: Connecting an ObjectComponents application object to the main window (container)

In order for the application’s main window to receive OLE messages, it must be connected to an ObjectComponents application (TOcApp) object.

To connect a TOcApp object to the main window,

1.	Declare the TOcApp object.

For example, the following line declares a TOcApp object called OcApp:

TOcApp*       OcApp       = 0;

2.	When the main window is created, call the SetupWindow method of the TOcApp object.

In the CPPOCF1.CPP example, the SetupWindow method is called from the MainWnd_OnCreate function:

bool

MainWnd_OnCreate(HWND hwnd, CREATESTRUCT FAR* /*lpCreateStruct*/)

{

  	HwndMain = hwnd;

  if (OcApp)

  	  OcApp->SetupWindow(hwnd);

  return true;

}

Note: The actual TOcApp object is created by the registrar object in the WinMain function. (You’ll learn more about the registrar object later.)

In an SDI application like CPPOCF1, the main window controls the view window. (Every ObjectComponents application needs an application window and a view window, as detailed in the next step.) When the main window receives a WM_SIZE message, it moves the view to keep it aligned with the client area of the main window. When the main window receives a WM_CLOSE message, it destroys both itself and the view window.

void

MainWnd_OnSize(HWND hwnd, UINT /*state*/, int /*cx*/, int /*cy*/)

{

  if (IsWindow(HwndView)) {

    TRect rect;

    GetClientRect(hwnd, &rect);

    MoveWindow(HwndView, rect.left, rect.top, rect.right, rect.bottom, true);

  }

}

void

MainWnd_OnClose(HWND hwnd)

{

  if (IsWindow(HwndView))

    DestroyWindow(HwndView);

  DestroyWindow(hwnd);

}

In an MDI application, each child window creates its own view window. The child window does what the main window does in an SDI application: it creates and manages a view for the information it displays.

When the main window is destroyed, it should release the TOcApp object.

You shouldn't call delete for a TOcApp object because the OLE system might still need more information before it allows the view to shut down. ReleaseObject tells the TOcView object that you don't need it any longer. The view subsequently destroys itself as soon as all other OLE clients finish with it. The TOcApp destructor is protected to prevent you from calling it directly.


Connecting an ObjectComponents view object to the view window (container)
Step 5: Connecting an ObjectComponents view object to the view window (container)

A container must have a view window that is separate from its main window. Usually the view window has an invisible border and it exactly fills the client area of the main window. From the user's point of view, there is only one window in the application. But ObjectComponents expects to send some event messages to the main window and some to the view window.

In order for a view window to receive OLE messages, it must be connected to an ObjectComponents view object. (TOcView for an OLE container or a TOcxView for an OCX container.)

And in order for a view object to keep track of the objects it contains, it must be connected to an ObjectComponents document (TOcDocument) object.

To connect a TOcView object to the view window,

1.	Declare a TOcView object and a TOcDocument object:

TOcView*       OcView      = 0;

TOcDocument*   OcDoc       = 0;

2.	Create the TOcDocument and TOcView objects, and then call the SetupWindow method of the TOcView object:

You should call the SetupWindow method when the view window is created, as shown in the CPPOCF1.CPP example.

bool

ViewWnd_OnCreate(HWND hwnd, CREATESTRUCT FAR* /*lpCreateStruct*/)

{

OcDoc = new TOcDoc(*OcApp)

OcView = new TocView(*OcDoc)

if (OcView)

  OcView->SetupWindow(hwnd);

return true;

}

When the view window is destroyed, it should delete the TOcDocument object and release the TOcView object.

You shouldn't call delete for a TOcView object because the OLE system might still need more information before it allows the view to shut down. ReleaseObject tells the TOcView object that you don't need it any longer. The view subsequently destroys itself as soon as all other OLE clients finish with it. The TOcView destructor is protected to prevent you from calling it directly.

void

ViewWnd_OnDestroy(HWND /*hwnd*/)

{

.

.

  if (OcView)

    OcView->ReleaseObject();  // release the COM object.

}


Handling OLE messages (container)
Step 6: Handling OLE messages (container)

To handle OLE messages, you must:

1. Handle the WM_OCEVENT message message in the main window and view window procedures. (Whenever an OLE event occurs, a WM_OCEVENT message is sent to the main window procedure and the view window procedure by the TOcApp and TOcView objects respectively.)

2. Create a function to handle specific OLE messages.

3. Create a function that corresponds to each OLE message that you handle in step 2.

This is how OLE messages are handled in the CPPOCF.CPP example:

First, the WM_OCEVENT message is handled in the main window procedure and the view window procedure.

long CALLBACK _export

MainWndProc(HWND hwnd, uint message, WPARAM wParam, LPARAM lParam)

{

  switch (message) {

    // General message handlers:

    HANDLE_MSG(hwnd, WM_CREATE,  MainWnd_OnCreate);

    HANDLE_MSG(hwnd, WM_CLOSE,   MainWnd_OnClose);

    HANDLE_MSG(hwnd, WM_DESTROY, MainWnd_OnDestroy);

    HANDLE_MSG(hwnd, WM_COMMAND, MainWnd_OnCommand);

    HANDLE_MSG(hwnd, WM_SIZE,    MainWnd_OnSize);

    // The OLE message handler:

    HANDLE_MSG(hwnd, WM_OCEVENT, MainWnd_OnOcEvent);

}

  return DefWindowProc(hwnd, message, wParam, lParam);

}

long CALLBACK _export

ViewWndProc(HWND hwnd, uint message, WPARAM wParam, LPARAM lParam)

{

  switch (message) {

    // General message handlers:

    HANDLE_MSG(hwnd, WM_CREATE,  ViewWnd_OnCreate);

    HANDLE_MSG(hwnd, WM_CLOSE,   ViewWnd_OnClose);

    HANDLE_MSG(hwnd, WM_DESTROY, ViewWnd_OnDestroy);

    HANDLE_MSG(hwnd, WM_COMMAND, ViewWnd_OnPaint);

    // The OLE message handler:

    HANDLE_MSG(hwnd, WM_OCEVENT, MainWnd_OnOcEvent);

}

  return DefWindowProc(hwnd, message, wParam, lParam);

}

Note: The HANDLE_MSG macro is defined in the ocf/ocfevx.h file.

Second, specific OLE messages are handled in the MainWnd_OnOcEvent and ViewWnd_OnOcEvent functions.

long

MainWnd_OnOcEvent(HWND hwnd, WPARAM wParam, LPARAM /*lParam*/)

{

  switch (wParam) {

    HANDLE_OCF(hwnd, OC_VIEWTITLE, MainWnd_OnOcViewTitle);

  }

  return true;

}

long

MainWnd_OnOcEvent(HWND hwnd, WPARAM wParam, LPARAM /*lParam*/)

{

  switch (wParam) {

    HANDLE_OCF(hwnd, OC_VIEWCLOSE, MainWnd_OnOcViewClose);

    HANDLE_OCF(hwnd, OC_VIEWTITLE, MainWnd_OnOcViewTitle);

  }

  return true;

}

Note: The HANDLE_OCF macro is defined in the ocf/ocfevx.h file.

Third, the MainWnd_OnOcViewTitle, ViewWnd_OnViewTitle, and ViewWnd_OnOcViewClose functions correspond to the OLE messages that are handled in the code shown above.

const char*

MainWnd_OnOcViewTitle(HWND /*hwnd*/)

{

  return APPSTRING;

}

const char*

ViewWnd_OnOcViewTitle(HWND /*hwnd*/)

{

  return APPSTRING;

}

const char*

MainWnd_OnOcViewClose(HWND /*hwnd*/)

{

  if (OcDoc)

    OcDoc->Close

return true;

}

Therefore, the CPPOCF application returns the string defined in APPSTRING whenever the main window or the view window receives the OC_VIEWTITLE message.

Note: Most containers handle the OC_VIEWTITLE message in the view window only.

And the view window closes itself when it receives the OC_VIEWCLOSE message.

For a list of OLE messages that can be sent to the main window and view window, see the OC_APPxxxx Messages and OC_VIEWxxxx Messages topics.

Using the new message-handling classes

You can also handle OLE messages by implementing the virtual functions of the TOcContainerHost class.


Handling OLE menu commands
Step 7: Handling OLE menu commands

To specify how an application responds to OLE menu commands, you must:

1. Handle the WM_COMMAND message in the main window procedure.

2. Create a function to handle specific menu commands.

This is how OLE messages are handled in the CPPOCF1.CPP example:

First, the WM_COMMAND message is handled in the main window procedure:

long CALLBACK _export

MainWndProc(HWND hwnd, uint message, WPARAM wParam, LPARAM lParam)

{

  switch (message) {

    HANDLE_MSG(hwnd, WM_CREATE,  MainWnd_OnCreate);

    HANDLE_MSG(hwnd, WM_CLOSE,   MainWnd_OnClose);

    HANDLE_MSG(hwnd, WM_DESTROY, MainWnd_OnDestroy);

    // The WM_COMMAND message handler:

    HANDLE_MSG(hwnd, WM_COMMAND, MainWnd_OnCommand);

    HANDLE_MSG(hwnd, WM_SIZE,    MainWnd_OnSize);

HANDLE_MSG(hwnd, WM_OCEVENT, MainWnd_OnOcEvent);

}

  return DefWindowProc(hwnd, message, wParam, lParam);

}

Note: The HANDLE_MSG macro is defined in the ocf/ocfevx.h file.

Second, specific menu commands are handled in the MainWnd_OnCommand function. (In this case, CM_INSERTOBJECT OLE is the only OLE command that is handled.)

void

MainWnd_OnCommand(HWND hwnd, int id, HWND /*hwndCtl*/, uint /*codeNotify*/)

{

  switch (id) {

    case CM_INSERTOBJECT: {

      try {

        TOcInitInfo initInfo(OcView);  // Initializing info structure

        if (OcApp->Browse(initInfo)) { // Show Insert Object dialog.

          TRect rect(30, 30, 100, 100);

          new TOcPart(*OcDoc, initInfo, rect);  // add object to doc.

        }

      }

      catch (TXBase& xbase) {

        MessageBox(GetFocus(), xbase.why().c_str(), "Exception caught", MB_OK);

      }

      break;

    }

    case CM_EXIT: {

      PostMessage(hwnd, WM_CLOSE, 0, 0);

      break;

    }

  }

}

Handling the InsertObject command

The code for inserting, dropping, or pasting an object into a document always begins with a TOcInitInfo structure. TOcInitInfo holds information describing the object about to be created: what container will receive it, whether to link or embed it, whether it already exists or will be newly created, and if it exists, where the data resides and in what format.

The constructor for TOcInitInfo receives a pointer to the view where you want the new object to appear. The next command, OcApp->Browse, invokes the standard Insert Object dialog box offering the user a choice of all the objects any server registered in the system can create. When the user chooses one, the Browse command places more information in initInfo.

The final step to insert a new OLE object is to create a TOcPart connector. TOcPart implements all the OLE services that a linked or embedded object is required to provide. It plugs into OLE, gets the data for the new object, adds itself to the list of parts in OcDoc, and draws itself on the screen in the position given by TRect.

Handling other OLE commands

For examples showing how to implement other OLE Edit menu commands, look at the source code for event handlers in OWL/OLEWINDO.CPP.


Creating a registrar object (container)
Step 8: Creating a registrar object (container)

The registrar (TOcRegistrar) object records information about the application in the system registration database, processes any OLE switches on the application's command line, and notifies OLE that the application is running.

Before you create a TOcRegistrar object, you must declare it.

The following line declares a TOcRegistrar object called OcRegister:

TOcRegistrar* OcRegistrar = 0;

After you declare the TOcRegistrar object, create the object in WinMain. Then, instead of entering a message loop, call the Run method of the object.

When the Run method returns, the application is ready to shut down. Delete the registrar object before exiting the application.

The WinMain function of the CPPOCF1 example shows all the steps:

int PASCAL

WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,

  char far* lpCmdLine, int nCmdShow)

{

  try {

  TOLEAllocator allocator(0);

  MSG msg;

    // Initialize OCF objects

    OcRegistrar = new TOcRegistrar(::AppReg, 0,

                                   string(lpCmdLine), 0);

    OcRegistrar->CreateOcApp(OcRegistrar->GetOptions(), OcApp);

      // per-instance and per-task initialization code goes here

    // Standard Windows message loop

    while (GetMessage(&msg, 0, 0, 0)) {

      TranslateMessage(&msg);

      DispatchMessage(&msg);

    }

  }

  catch (TXBase& xbase) {

    MessageBox(GetFocus(), xbase.why().c_str(), "Exception caught", MB_OK);

  }

  // free the registrar object

  delete OcRegistrar;

  return 0;

}


Compiling and linking the application (container)
Step 9: Compiling and linking the application (container)

Compile the container with the medium or large memory model.

Link the container to the OLE and ObjectComponents libraries.


Turning a C++ Application Into an OLE Server
Turning an application into an OLE server using ObjectComponents

See also

Follow these steps to turn an application into an OLE server using ObjectComponents:

1. Include ObjectComponents header files.

2. Create an OLE memory allocator object.

3. Create OLE registration tables and a document list object.

4. Connect an ObjectComponents application object to the main window.

5. Connect an ObjectComponents view object to the view window.

6. Handle OLE messages.

7. Create a factory callback function.

8. Create an ObjectComponents registrar object.

9. Compile and link the application.

Note: If you’re creating a new application, consider using AppExpert to save some work.

The topics that follow use code from the examples in the EXAMPLES/OCF/CPPOCF directory:

Example	Description

CPPOCF0	A basic windows application.

CPPOCF1	The CPPOCF0 example turned into a basic OLE container that registers itself in the system’s registration database, creates objects to initialize a new document, and allows standard OLE objects to be embedded.

CPPOCF2	The CPPOCF1 example turned into a basic OLE server.


Including ObjectComponents header files (server)
Step 1: Including ObjectComponents header files (server)

See also

An OLE server must include the following ObjectComponents header files:

#include <ocf/ocapp.h>    // TOcRegistrar, TOcModule, TOcApp

#include <ocf/ocreg.h>    // registration constants & app mode flags

#include <ocf/ocdoc.h>    // TOcDocument

#include <ocf/ocview.h>   // TOcView

#include <ocf/ocpart.h>   // TOcPart

#include <ocf/ocremvie.h> // TOcRemView

#include <ocf/ocfevx.h>   // WM_OCEVENT message crackers


Creating an OLE memory allocator object (server)
Step 2: Creating an OLE memory allocator object (server)

An OLE application should create an OLE memory allocator (TOleAllocator) object to initialize the OLE libraries. To create a TOleAllocator object, add this line to the application’s WinMain function.

TOleAllocator OleAlloc(0);


Creating registration tables and a document list object (server)
Step 3: Creating registration tables and a document list object (server)

See also

Like any other OLE application, an OLE server must register information about itself in the system’s registration database. Registration is performed automatically by ObjectComponents if you create a registration table for the application and each of its document types, and then pass the resulting structures to a registrar object. (You will learn more about the registrar object later.)

To create a registration table, use the BEGIN_REGISTRATION macro.

This is the application registration table used in the CPPOCF2.CPP example:

BEGIN_REGISTRATION(AppReg)

  REGDATA(clsid,   "{BD5E4A81-A4EF-101B-B31B-0694B5E75735}")

  REGDATA(progid,  APSTRING".Application"

END_REGISTRATION

Note: For an OLE server, you must specify the class id and progid keys in the application registration table. For more information, see the Registration Keys topic.

This is the document registration table used in the CPPOCF2.CPP example.

BEGIN_REGISTRATION(DocReg)

  REGDATA(description,  "Sample C Server Document")

  REGDATA(progid,       APPSTRING".Document.1")

  REGDATA(menuname,     "CServer")

  REGDATA(insertable,   "")

  REGDATA(verb0,        "&Edit")

  REGDATA(verb1,        "&Open")

  REGDATA(extension,    "scd")

  REGDATA(docfilter,    "*.scd")

  REGDOCFLAGS(dtAutoDelete | dtUpdateDir | dtCreatePrompt | dtRegisterExt)

  REGFORMAT(0, ocrEmbedSource,  ocrContent, ocrIStorage, ocrGet)

  REGFORMAT(1, ocrMetafilePict, ocrContent, ocrMfPict,   ocrGet)

END_REGISTRATION

Note: for an OLE server, you must specify the progid, description, menu name, insertable, extension, and formatn keys in the document registration tables. For more information, see the Registration Keys topic.

To accommodate servers with many document types, the registrar accepts a pointer to a linked list of all the application's document registration structures. Each node in the list is a TRegLink object. Each node contains a pointer to one document registration structure and another pointer to the next node.

TRegLink *RegLinkHead = 0;

TRegLink  regDoc(DocReg, RegLinkHead);

RegLinkHead points to the first node of the linked list. RegDoc is a node in the linked list. The TRegLink constructor follows RegLinkHead to the end of the list and appends the new node. Each node contains a pointer to a document registration structure. In CPPOCF2, the list contains only one node because the server creates only one type of document. The node points to DocReg.


Connecting an ObjectComponents application object to the main window (server)
Step 4: Connecting an ObjectComponents application object to the main window

In order for the application’s main window to receive OLE messages, it must be bound to an ObjectComponents application (TOcApp) object.

To bind a TOcApp object to the main window,

1.	Declare the TOcApp object.

For example, the following line declares a TOcApp object called OcApp:

TOcApp*       OcApp       = 0;

2.	Bind the TOcApp object to the main window using the SetupWindow method.

You should call the SetupWindow method when the main window is created. For example, in the CPPOCF1.CPP file, the MainWnd_OnCreate function, which is called when the main window receives a WM_CREATE message, calls the SetupWindow method.

bool

MainWnd_OnCreate(HWND hwnd, CREATESTRUCT FAR* /*lpCreateStruct*/)

{

  	HwndMain = hwnd;

  if (OcApp)

  	  OcApp->SetupWindow(hwnd);

  return true;

}

Note: The actual TOcApp object is created by the registrar object in the WinMain function. (You’ll learn more about the registrar object later.)

In an SDI application like the CPPOCF2 sample program, the main window controls the view window. (Every ObjectComponents application needs an application window and a view window, as detailed in the next step.) When the main window receives a WM_SIZE message, it moves the view to keep it aligned with the client area of the main window. When the main window receives a WM_CLOSE message, it destroys both itself and the view window.

void

MainWnd_OnSize(HWND hwnd, UINT /*state*/, int /*cx*/, int /*cy*/)

{

  if (IsWindow(HwndView)) {

    TRect rect;

    GetClientRect(hwnd, &rect);

    MoveWindow(HwndView, rect.left, rect.top, rect.right, rect.bottom, true);

  }

}

void

MainWnd_OnClose(HWND hwnd)

{

  if (IsWindow(HwndView))

    DestroyWindow(HwndView);

  DestroyWindow(hwnd);

}

In an MDI application, each child window creates its own view window. The child window does what the main window does in an SDI application: it creates and manages a view for the information it displays.

When the main window is destroyed, it should release the TOcApp object.

You shouldn't call delete for a TOcApp object because the OLE system might still need more information before it allows the view to shut down. ReleaseObject tells the TOcView object that you don't need it any longer. The view subsequently destroys itself as soon as all other OLE clients finish with it. The TOcApp destructor is protected to prevent you from calling it directly.


Connecting an ObjectComponents view object to the view window (server)
Step 5: Connecting an ObjectComponents view object to the view window (server)

A server must have a view window that is separate from its main window. Usually the view window has an invisible border and it exactly fills the client area of the main window. From the user's point of view, there is only one window in the application. But ObjectComponents expects to send some event messages to the main window and some to the view window.

In order for a view window to receive OLE messages, it must be connected to an ObjectComponents view (TOcRemView) object.

And in order for a view object to keep track of the objects it contains, it must be connected to an ObjectComponents document (TOcDocument) object.

To connect a TOcRemView object to the view window,

1.	Declare a TOcRemView object and a TOcDocument object:

TOcRemView*    OcRemView   = 0;

TOcDocument*   OcDoc       = 0;

2.	Create the TOcDocument and TOcRemView objects, and then call the SetupWindow method of the TOcRemView object:

You should call the SetupWindow method in the factory callback function, as shown in the CPPOCF2.CPP example. (The factory callback function is described later.)

HWndView  = CreateViewWindow(HwndMain);

OcDoc     = new TOcDoc(*OcApp);

OcRemView = new TocRemView(*OcDoc, &DocReg);

if (IsWindow(HWndView))

  OcRemView->SetupWindow(HwndView);

When the view window is destroyed, it should delete the TOcDocument object and release the TOcRemView object.

You shouldn't call delete for a TOcRemView object because the OLE system might still need more information before it allows the view to shut down. ReleaseObject tells the TOcRemView object that you don't need it any longer. The view subsequently destroys itself as soon as all other OLE clients finish with it. The TOcRemView destructor is protected to prevent you from calling it directly.

void

ViewWnd_OnDestroy(HWND /*hwnd*/)

{

.

.

  if (OcRemView)

    OcRemView->ReleaseObject();  // release the COM object.

  OcDoc->Close(); // release the server for each embedded object

  delete OcDoc;   // delete the document object

}


Handling OLE messages (server)
Step 6: Handling OLE messages (server)

Because the TOcRemView::SetupWindow method connected the OcRemView object to the view window, the object sends its event notification messages to the window. All ObjectComponents events are sent in the WM_OCEVENT message, so the view window procedure must respond to WM_OCEVENT.

long CALLBACK _export

ViewWndProc(HWND hwnd, uint message, WPARAM wParam, LPARAM lParam)

{

  switch (message) {

.

.

.  // other message crackers go here

    HANDLE_MSG(hwnd, WM_OCEVENT,  ViewWnd_OnOcEvent);

  }

  return DefWindowProc(hwnd, message, wParam, lParam);

}

The HANDLE_MSG message cracker macro for WM_OCEVENT is defined in the ocf/ocfevx.h header. The same header also defines a another cracker for use in the WM_OCEVENT message handler.

// Subdispatch OC_VIEWxxxx messages

long

ViewWnd_OnOcEvent(HWND hwnd, WPARAM wParam, LPARAM /*lParam*/)

{

  switch (wParam) {

    // insert an event cracker for each OC_VIEWxxxx message you want to handle

    HANDLE_OCF(hwnd, OC_VIEWCLOSE, ViewWnd_OnOcViewClose);

  }

  return true;

}

Handling Selected Application Events

The only ObjectComponents event that CPPOCF2 can handle in its main window is OC_APPSHUTDOWN. A server receives this message when the last linked or embedded object closes down. If the server was launched by OLE, it can terminate. If user launched the server directly, the server doesn't need to do anything.

const char*

MainWnd_OnOcAppShutDown(HWND hwnd)

{

  if (OcRegistrar->IsOptionSet(amEmbedding))

    DestroyWindow(hwnd);

}

The registrar sets the amEmbedding flag at startup if it finds the  -Embedding switch on the application's command line. OLE pass the -Embedding switch when it launches a server to support a linked or embedded object.

Handling Selected View Events

Each HANDLE_OCF macro calls a different handler function. In the example, the handler function is called ViewWnd_OnOcViewClose.

bool

ViewWnd_OnOcViewClose(HWND hwnd)

{

  DestroyWindow(hwnd);

  return true;

}

A server receives this message when a container closes the document that contains the server's object. CPPOCF2 responds by closing the view window. The WM_DESTROY handler also deletes or releases the helper objects associated with the server document.

Painting the Document

No special code is required in the server's paint procedure. It always paints its document the same way, whether or not it is painting an embedded object.

void

ViewWnd_OnPaint(HWND hwnd)

{

  PAINTSTRUCT ps;

  HDC dc = BeginPaint(hwnd, &ps);

  wsprintf(Buffer, "%u", Counter);

  TextOut(dc, 0, 0, Buffer, lstrlen(Buffer));

  EndPaint(hwnd, &ps);

}

When the view window is created, it starts off a timer. Every time the view receives a WM_TIMER message, it increments the value in the global variable Counter and calls InvalidateRect to make the view repaint itself. On each call, the paint procedure prints the value of Counter.

Using the new message-handling class

You can also handle OLE messages by implementing the virtual functions of TOcServerHost, a new ObjectComponents event-handling class.


Creating a factory callback function
Step 7: Creating a factory callback function

The factory callback is a function you implement and pass to the constructor of a registrar object. When it is time for the application to run, or when a container tries to insert one of the server's objects, ObjectComponents invokes the callback function.

The factory callback decides what to do by reading the parameters it receives and examining the running mode flags the registrar has set. The callback is called a factory because it creates OLE component objects on request.

The requirement that every ObjectComponents application must supply a factory callback function unifies the process of creating objects. Normally the process varies depending on whether the application is a container or a server, whether it is automated, whether it is running as a DLL or an executable program, and whether the application was invoked by the user directly or by OLE. The factory callback makes it possible to revise and run the application in a variety of ways without rewriting any code. For more information about factory callbacks, look up "Factory Templates" in the ObjectWindows Reference Guide.

A set of factory templates such as TOleFactory and TOleAutoFactory make it easy to implement factories for ObjectWindows programs, but in a straight C++ program you have to write the factory yourself.

Factory callback procedures can have any name you like, but they must follow this prototype:

IUnknown* ComponentFactory(IUnknown* outer, uint32 options, uint32 id);

outer is used when aggregating OLE objects to make them function as a single unit. The factory's return value is also used for aggregation. Because containers don't aggregate, CPPOCF1 ignores outer and returns 0.

options contains the bit flags that indicate the application's running mode. The registrar object sets the flags when it processes the command line switches, before it calls the factory callback. The factory tests the flags to find out what it should do. The possible flags are defined by the TOcAppMode enumerated type, and they have names like amRun and amShutdown.

id is an identifier that tells the factory what kind of object to create.

The factory's parameters can direct the factory to perform one of three actions:

Initialize the application. The first time it runs, the factory creates a TOcModule object. TOcModule connects the application to the OLE system by creating a TOcApp connector object. The factory also handles aggregation in this phase.

Run the application. If the amRun flag is set, the factory enters the message loop. If the server is built as a DLL, then when OLE loads the server the registrar does not set the amRun flag and the server should not run its own message loop.

Create an object. The id parameter tells the factory what kind of object to create. Because CPPOCF2 creates only one kind of object, it checks only whether id is greater than 0. In applications that register multiple document templates, id points to the template for the requested object.

The factory callback in CPPOCF2 refers to four global variables. One is OcRegistrar. Another is OcApp.

TOcRegistrar* OcRegistrar = 0;

TOcApp*       OcApp       = 0;

TOcApp is the connector object that implements OLE interfaces on behalf of the application. One of the factory's jobs is to create the connector object when the application starts and to destroy it when the application shuts down.

Here is the factory callback from CPPOCF2:

IUnknown*

ComponentFactory(IUnknown* outer, uint32 options, uint32 id)

{

  IUnknown* ifc = 0;

  // start the application or shut it down

  if (!OcApp) {

    if (options & amShutdown)  // no app to shutdown!

      return 0;

    OcRegistrar->CreateOcApp(options, OcApp);

  } else if (options & amShutdown) {

    DestroyWindow(HwndMain);

    return 0;

  }

  // aggregate if an outer pointer was passed

  if (id == 0)

    OcApp->SetOuter(outer);

  // enter message loop if the run flag is set

  if (options & amRun) {

    if ((options & amEmbedding) == 0) {

      HwndView = CreateViewWindow(HwndMain);

    }

    MSG msg;

    // Standard Windows message loop

    while (GetMessage(&msg, 0, 0, 0)) {

      TranslateMessage(&msg);

      DispatchMessage(&msg);

    }

  }

  // create a document if the id parameter is non-zero

  if (id) {

    OcDoc     = new TOcDocument(*OcApp);

    HwndView  = CreateViewWindow(HwndMain);

    OcRemView = new TOcRemView(*OcDoc, &DocReg);

    if (IsWindow(HwndView))

      OcRemView->SetupWindow(HwndView);

    ifc = OcRemView->SetOuter(outer);

  }

  return ifc;

}

The factory's outer parameter is 0 unless some other object is aggregating with the newly created object. Aggregated objects are components that act together as a single unit. Objects can form aggregations at run time; you do not need access to an object's source code to aggregate with it. ObjectComponents supports aggregation by passing outer to the application factory. If outer is non-zero, it points to the IUnknown interface of anther object that wants the newly created object to subordinate itself. To allow aggregation, the factory calls the SetOuter method on the object it is creating, either TOcApp or TOcRemView. SetOuter returns a pointer to the object's own IUnknown interface. The factory should return the same pointer, too.

Note:	TOcApp::SetOuter is only called when an application automates itself. CPPOCF2 includes the call anyway in case the application later becomes an automation server.


Creating an ObjectComponents registrar object (server)
Step 8: Creating an ObjectComponents registrar object (server)

The registrar (TOcRegistrar) object records information about the application in the system registration database, processes any OLE switches on the application's command line, and notifies OLE that the application is running.

Before you create a TOcRegistrar object, you must declare it.

The following line declares a TOcRegistrar object called OcRegister:

TOcRegistrar* OcRegistrar = 0;

After you declare the TOcRegistrar object, create the object in WinMain. Instead of entering a message loop, call the Run method of the object.

When the Run method returns, the application is ready to shut down. Delete the registrar object before exiting the application.

This excerpt from the CPPOCF1 WinMain function shows all the steps:

int PASCAL

WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,

  char far* lpCmdLine, int nCmdShow)

{

  try {

  TOLEAllocator allocator(0);

  MSG msg;

    // Initialize ObjectComponents objects

    OcRegistrar = new TOcRegistrar(::AppReg, ComponentFactory,

                                   string(lpCmdLine), ::RegLinkHead,
                                   hInstance);

    if (OcRegistrar->IsOptionSet(amEmbedding))

      nCmdShow = SW_HIDE;

    // per-instance and per-task initialization code goes here

    OcRegistrar->Run();

    // free the registrar object

    delete OcRegistrar;

  }

  catch (xmsg& x) {

    MessageBox(GetFocus(), x.why().c_str(),"Exception caught", MB_OK);

  }

  return 0;

}


Compiling and linking (server)
Step 9: Compiling and linking the application (server)

Link the server to the OLE and ObjectComponents libraries.


Making a DLL Server
Creating a DLL OLE server

Typically, linking and embedding servers are standalone executables that can be launched directly by the user or invoked indirectly by an OLE container. You can also implement an OLE server in a DLL. A server built as a DLL is sometimes called an in-process server because DLL code runs in the same process as its client. The terms EXE server and server application refer specifically to a server implemented in an EXE. ObjectComponents allows you to create both EXE and DLL servers. If you are using ObjectWindows, converting from one to the other requires only two simple changes.

Note:	The discussion and instructions that follow apply to automation servers as well as linking and embedding servers.

The following topics discuss more about making a DLL server:

Pros and Cons of DLL Servers

Debugging a DLL Server

Tools for DLL Servers

Pros and Cons of DLL Servers

Advantages

The major advantage of DLL servers is performance. Because a DLL server lives in the address space of the container,it loads and responds very fast. An EXE server, on the other hand, is a  separate process and requires some form of intertask communication to interact with a container. OLE serializes intertask calls and marshals the function calls with their parameters, packaging them into the proper format for the interprocess protocol. (The protocol it uses is called LRPC, for Lightweight Remote Procedure Call.) the process of serializing the drawing commands in a metafile is particularly slow, so DLL servers substantially increase the speed of creating presentation data for linked and embedded objects.

Disadvantages

There are a few disadvantages to using a DLL server, however. While OLE supports interaction between 16-bit and 32-bit executable applications, a 16-bit Windows application cannot use a 32-bit DLL server and a Win32 application cannot use a 16-bit DLL server. Also, DLLs do not have message queues. As a result, a DLL server cannot easily perform a task in the background. ObjectWindows overcomes this limitation by running a timer so that it can still call the IdleAction methods of objects derived from TApplication or TOleFrame. (ObjectWindows also uses the timer for internal processes such as command-enabling for tool bars, deleting condemned windows, and resuming thrown exceptions.)

Because a DLL server becomes part of the container's process, bugs in one can interfere with the other, making DLL servers sometimes harder to debug.

DLL servers also present user interface dilemmas. For example, when a container initiates an open edit session with a server, it doesn't matter to the user whether the server is an EXE or a DLL; the user interface for open editing is the same either way. But the lifetime of a DLL server is tied to the container that loads it. When the container quits, the server DLL is unloaded. That can cause problems if the server's user interface normally allows the user to edit serveral documents at once. If the user were to create a new document while editing an embedded object, the user might want to continue editing the new document even after the container quits, but then the server is no longer in memory. This is a particular problem for MDI servers because the MDI interface allows users to open multiple documents in a single session. Typically DLL servers do not allow multidocument editing.

Finally, DLL servers have one other disadvantage. While OLE 2 provides a compatibility layer to let OLE 2 servers interact with OLE 1 clients, the compatibility layer works only for EXE servers. A DLL server cannot support an OLE 1 client.


Debugging a DLL Server
Debugging a DLL OLE server

The same general techniques used to debug DLLs apply to DLL servers. The steps that follow describe one approach, using Turbo Debugger for Windows to set breakpoints in a DLL server.

1.	Build and register the DLL server.

a.	Build your server with debugging information.

b.	Register the server using the REGISTER.EXE utility.

c.	Verify that the registration was successful by running RegEdit and looking for your servers file types. (RegEdit is a registration editor included with Windows.)

2.	Launch Turbo Debugger for Windows and load a container.

Select the File|Open menu option and enter the container's name in the Program Name field and click the OK button.

The debugger loads the container. If the container was built without debugging information, you may receive a warning. You can safely ignore it.

3.	Load the server's debugging information.

a.	Select View|Module from the debugger's main menu. This activates the dialog titled "Load module source or DLL symbols." (You can also activate the module dialog by pressing F3.)

b.	Enter the full name of DLL server file in the DLL Name field.

c.	Select the Yes option in the Debug Startup field and click the Add DLL button. The name of your DLL server (followed by !!) appears as the selected entry in the DLLs & Programs list.

d.	Click the Symbol Load button.

If you receive an error message indicating that the DLL is not loaded , press the Escape key to return to the debugger's main menu and proceed to the next step. Otherwise, skip the next step and proceed to step 5.

Note:	If you did not receive the error message that the DLL is not loaded, then your DLL server was already in memory before the container activated it. This happens if another container is currently running with one of your server's objects. More often, however, it indicates that your server crashed or was improperly terminated in an earlier session.

4.	Run the container and insert one of your server's objects.

a.	Select the Run|Run menu option (or press F9) to start the container.

b.	Choose Insert Object from the container's Edit menu and insert your server's object.

The debugger pops up as soon as OLE loads your DLL server.

5.	Display the DLL source modules and set breakpoints.

a.	Choose View|Module from the container's main menu to see the names of the source files used to build your server. The file names appear in Source Modules list.

b.	Select source files by double-clicking the file names.

c.	Set breakpoints in your server.

d.	Choose the Run|Run menu option (or press F9) to return control to the container application.

6.	If you skipped step 4, insert one of your server's objects into the container now.

The debugger stops at the breakpoints set in your source files and allows you to step through your server, inspect variables, and verify the logic of your code.


Tools for DLL Servers
Tools for DLL OLE servers

Before running your DLL server, you must record its registration information in the system registration database. The Register tool does that for you. Another tool, DllRun, gives you the option of running your DLL server at any time as a standalone application, which is sometimes convenient for testing.

REGISTER.EXE

The REGISTER.EXE utility registers an ObjectComponents DLL server. On the command line, pass Register the name of your server followed by the -RegServer switch. Here is the command to register Tic Tac Toe:

register ttt.dll -RegServer

Even though the Register utility is a Windows application, not a DOS application, you can invoke it from a Windows DOS box. This ability is useful in makefiles. (To invoke other Windows programs from a DOS box command line, use the WinRun utility described in UTILS.TXT.)

Register can also unregister your server. Unregistering removes all entries related to your server from the registration database. It's good practice to unregister one version before you register the next. To unregister, use the -UnregServer switch. This command unregisters Tic Tac Toe:

register ttt.dll -UnregServer

DLLRUN.EXE

The DLLRUN.EXE utility lets you load and run an ObjectComponents DLL server as though it were a standalone executable program. The ability to run in executable mode is useful for debugging. It also lets you give customers the choice of running your server either way without having to distribute two versions of the same application.

on the command line, pass DllRun the progid of the server. This is the value assigned to the progid key in the server's registration table. This command runs the Tic Tac Toe server:

dllrun TicTacToeDll

DllRun launches the DLL server in the executable running mode. The running mode of an ObjectComponents application is represented by a set of bit flags that you can test by calling TOcModule::IsOptionSet. (Remember that the application object of a linking and embedding program derives from both TApplication and TOcModule.)

The running mode bit flags are defined in the TOcAppMode enum. AmEmbedded is set when the server is invoked by OLE, not by the user. AmExeModule is set in an application that was built as an EXE. AmExeMode is set in an application that is running as a stand-alone executable, even if it was built as a DLL.

This code tests the flags to determine the server's running mode.

void

TMyApp::TestMode()

{

  if (IsOptionSet(amExeMode))            // is server running as an EXE?

    if (!IsOptionsSet(amExeModule)) {    // if so, was it built as an EXE?

      // the server is a DLL running in EXE mode

    } else {

      // the server was built as an EXE

  } else {

    // the server is a DLL running in a client's process

}


What is OLE?

OLE, which stands for object linking and embedding, is an operating system extension that lets applications achieve a high degree of integration. OLE defines a set of standard interfaces so that any OLE program can interact with any other OLE program. No program needs to have any built-in knowledge of its possible partners.

Programmers implement OLE applications by creating objects that conform to the Component Object Model (COM). COM is the specification that defines what an OLE object is. COM objects support interfaces, composed of functions for other objects to call. OLE defines a number of standard interfaces. COM objects intended for public access expose their interfaces in a registration database. Interfaces have unique identifiers to distinguish them.

ObjectComponents encapsulates the COM specification for creating objects and provides default implementations of the interfaces used for two common OLE tasks: linking and embedding, and automation. Linking and embedding lets one application incorporate live data from other OLE applications in its documents. Automation lets one application issue commands to control another application.

The following topics discuss common uses for OLE.

Linking and Embedding

Linking and embedding refer to the transfer of data from one program to another. The first program, the server, sends its data to the second program, the container. For example, cells from a spreadsheet can be dropped into a word processing document. Of course you don't need OLE to pass data from one Windows program to another. You can do that much with just the Clipboard. The difference between OLE and the Clipboard is that in OLE the receiving program doesn't have to know anything at all about the format of the data in the object. Any OLE server application can give its data to any OLE container application. Thanks to OLE, the container doesn't care whether the object it receives is a metafile, a bitmap, or ASCII text. The server passes whatever data it uses internally and the container accepts it. Furthermore, the object remains dynamic even after being transplanted. When the container wants to display, modify, or save the object, it calls OLE to do it. OLE, working behind the scenes, calls the server to execute the user's command. The object belongs to the container's document, but OLE maintains a live connection back to the server. The user can continue to edit the object using all of the server's tools. As a result, the user can combine objects from different servers into a single document without losing the ability to update and modify any object as the document evolves.

Automation

Automation happens when one program issues commands to another. If you write a calculator program, for example, you might allow other programs to issue commands like these:

Press the nine button.

Press the plus button.

Press the six button.

Press the equals button.

Tell me what's in the Total window.

These are commands a person might normally issue through the calculator's user interface. With automation, the calculator exposes its internal functions to other programs. The calculator becomes an automation object, and programs that send commands to it are automation controllers. OLE defines standard interfaces that let a controller ask any installed server to create one of its objects. OLE also makes it possible for the controller to browse through a list of automated commands the server supports and execute them.


What does OLE look like?

See also

The linking and embedding features of OLE include a standard user interface for performing common operations such as placing OLE objects in container documents and activating them once they are linked or embedded. The OLE standards cover menu commands, dialog boxes, tool bars, drag and drop support, and painting conventions, so that the user interface for OLE operations is consistent across applications. Together, ObjectComponents and ObjectWindows execute most of the interface tasks for you.

Understanding OLE programming can be difficult without a clear grasp of the interface you are trying to create. The following sections present pictures of a container showing what happens onscreen at each step in a common sequence of OLE operations. The user runs a container, inserts objects from several OLE servers into the document, edits an object, and saves the document.


Inserting an object

What Does OLE Look Like?

 The example program called SdiOle is an OLE container using the single-document interface (SDI) and written with ObjectWindows and ObjectComponents. The source code for SdiOle is in EXAMPLES/OWL/OCF/ SDIOLE.

The SdiOle Edit menu contains five standard OLE commands that most containers possess: Paste Special, Paste Link, Insert Object, Links, and Object.

ObjectWindows implements all five of the standard commands for you if you like, but a container does not have to use them all.

Like the common dialog boxes in Windows for opening files and choosing fonts, the Insert Object dialog box is a standard resource implemented by the system. For consistency, it is best to use the standard dialog boxes unless your application has some unusual requirement that the standard dialog box does not meet.

The box under Object Type lists all the kinds of objects available in the system. Whenever a server installs itself, it tells the system what objects it can create. The system keeps this information in its registration database. The Insert Object dialog box queries the database and shows all the types that OLE can create for you using the available server applications.

In the illustration, the user has chosen to insert a Quattro Pro spreadsheet. The Result box at the bottom of the dialog box explains what will happen if the user clicks OK now. Because the Create New button is selected, clicking OK will embed a new, empty spreadsheet object into the user's open document.


Editing an object in place

What Does OLE Look Like?

The example program called SdiOle is an OLE container using the single-document interface (SDI) and written with ObjectWindows and ObjectComponents. The source code for SdiOle is in EXAMPLES/OWL/OCF/ SDIOLE.

The SdiOle Edit menu contains five standard OLE commands that most containers possess: Paste Special, Paste Link, Insert Object, Links, and Object.

If Quattro Pro is the server application that creates the active object, Quattro Pro will take over the SdiOle window and display its own menus and tool bars. All the Quattro Pro menu and tool bar commands can be executed right there in SdiOle. The feature of OLE that lets a server take over a container's main window is called in-place editing. It lets the user edit the object in its place, without switching back and forth between different windows. The programming task that makes this possible is called menu merging, combining menus from two programs in one menu bar.

Although many programs let you paste data from other programs into your documents, without OLE you cannot continue to edit the objects after they are transferred.

SdiOle is a very simple application and knows nothing about columns and rows or fonts and shading. But, even though the Quattro Pro server created and formatted the object, that data in the object belongs to the container. When the user chooses File|Save from the SdiOle menu bar, what gets written is an SdiOle document, not a Quattro Pro document. With the help of ObjectComponents and the OLE system, SdiOle marks an area in its own file to store the data for the embedded object. When the user chooses File|Load to reload the same document, the spreadsheet cells will still be there. If the user tries to edit the object again, OLE invokes Quattro Pro to take over the SdiOle window once more. The object remains associated with the application that created it even though the object is stored in a foreign file.

When OLE places the data for an object directly into the container's document as it has the data for this spreadsheet, the object is said to be embedded. Besides embedding, OLE also links objects to container documents.


Activating, deactivating, and selecting an object

What Does OLE Look Like?

The example program called SdiOle is an OLE container using the single-document interface (SDI) and written with ObjectWindows and ObjectComponents. The source code for SdiOle is in EXAMPLES/OWL/OCF/ SDIOLE.

The SdiOle Edit menu contains five standard OLE commands that most containers possess: Paste Special, Paste Link, Insert Object, Links, and Object.

An embedded object is outlined by a thick gray rectangle. The presence of this rectangle indicates that the object is active. The activation rectangle appears when you double-click the object. Usually activating an object initiates an editing session, but the server decides whether to follow that convention. For example, embedded sound objects might play when activated. In most cases, only one object can be active at a time.

When an activation rectangle has small black boxes spaced around it, they are called grapples. The user can resize the object by clicking a grapple and dragging the mouse. Also, the user can move the object by clicking anywhere else on the activation rectangle and dragging. ObjectWindows uses the TUIHandle class to draw rectangles and grapples around objects.

When the user clicks the mouse button outside the activated object, the activation rectangle goes away. The object is now inactive. Deactivating an object tells OLE that you are through editing. The server relinquishes its place, and the container's window returns to normal. The only commands on the menu bar are the ones SdiOle put there. The tool bar and window caption are back to normal, as well.

You can select an inactive object without activating it. When you press the mouse button over an inactive object, the container draws a thin black rectangle to show that you have selected it. Like the activation rectangle, it has grapples. The user can move and resize a selected object just like an active object.


Finding an object's verbs

What Does OLE Look Like?

The example program called SdiOle is an OLE container using the single-document interface (SDI) and written with ObjectWindows and ObjectComponents. The source code for SdiOle is in EXAMPLES/OWL/OCF/ SDIOLE.

The SdiOle Edit menu contains five standard OLE commands that most containers possess: Paste Special, Paste Link, Insert Object, Links, and Object.

When an object is selected, the container modifies its menus to offer a choice of whatever actions the object's server can do with the object. OLE calls these actions verbs. Conventionally, the container displays available verbs in two places: on its Edit menu and on a SpeedMenu. For example, if a SpeedMenu pops up when the user right clicks, the first three commands on the SpeedMenu are always Cut, Copy, and Delete. The fourth item, Notebook Object, changes depending on the object selected. When an object from Paradox is inserted, for example, the fourth item becomes Paradox 5 Object.

The smaller cascading menu lists the particular verbs that the server supports. Quattro Pro has only two verbs. It can edit an object or open an object. The Edit verb initiates an in-place editing session. The Open verb inititates an open editing session.

The final item, Convert, is the same for all objects. It invokes another standard OLE dialog box that lets the user convert an object from one server's data format to another. The Convert command is useful when, for example, you have Paradox installed on your machine, but someone gives you a compound document with an embedded object from some other database application. If Paradox knows how to convert data from the other database, then the Convert command binds the foreign database object to Paradox.

The speed menu for a selected object  shows where verbs appear on the Edit menu. When no object is selected, the last command on the Edit menu is disabled and says simply Object. When an object is selected, the Object command changes to describe the selected object. In the example, Object changes to Notebook Object.


Linking an object

What Does OLE Look Like?

The example program called SdiOle is an OLE container using the single-document interface (SDI) and written with ObjectWindows and ObjectComponents. The source code for SdiOle is in EXAMPLES/OWL/OCF/ SDIOLE.

The SdiOle Edit menu contains five standard OLE commands that most containers possess: Paste Special, Paste Link, Insert Object, Links, and Object.

By default, the Insert Object command creates a brand new empty object, and embeds it. Instead of embedding an object, you can choose to link it.

When OLE links an object, it does not store the object's data in the container's document. It stores only the name of the server file where the data is stored along with the location of the data within the file and a snapshot of the object as it appears onscreen. The snapshot is usually a metafile. The container doesn't receive a copy of the object; it receives a pointer to the object. OLE still draws the object in the container's document, just as though it was embedded, but the container doesn't own the data.

If the server document that holds the data for the linked object is deleted, then the user can no longer activate and edit the linked object. On the other hand, if the data in the server document is updated, then the updates appear automatically in all the container documents that have been linked to the same object. If several documents embed the same object, then they are creating copies, and changes made in one document have no effect on the copies in other documents.

What if you select the Create from File button in the Insert Object dialog box? Instead of creating a new empty object, you choose a file with existing data and OLE invokes the server that created the file. You can embed data from the file, but if the user has checked the Link box, when the user clicks OK, OLE does not copy data from CHECKS.DB into the server's document. It creates a link that refers back to the data stored in the original file.

The text in the Result box at the bottom of the dialog box explains what will happen when the user clicks OK. The EXAMPLE.DFL document now contains two OLE objects—the embedded Quattro Pro spreadsheet and the linked Paradox table.

Neither of the two objects is active. The spreadsheet is inactive and the database table is selected. Because the database table is linked, ObjectWindows draws the selection rectangle with a dashed line.


Opening an object to edit it

What Does OLE Look Like?

The example program called SdiOle is an OLE container using the single-document interface (SDI) and written with ObjectWindows and ObjectComponents. The source code for SdiOle is in EXAMPLES/OWL/OCF/SDIOLE.

The SdiOle Edit menu contains five standard OLE commands that most containers possess: Paste Special, Paste Link, Insert Object, Links, and Object.

TheEdit and Open are the two most common verbs, and Quattro Pro and Paradox, for example, both use them. Choosing the Open verb  makes the same table visible in two windows - the container window where it is linked and the server window where it is being edited. When finished editing in the server window, the user chooses File|Close and returns to the container. Any changes made during the editing session automatically appear in the container window afterward.

Contrast this editing session with another. In this session, the container window remains unchanged. The SdiOle window has only its own commands and its own tool bar. The editing takes place in a separate window that OLE opened just for this session. Returning to the server to edit is called open editing. Some servers support only open editing, not in-place editing.

These are common linking and embedding operations: the user links or embeds an object, selects it, activates it, edits it in place or open, and saves the compound document complete with its OLE object.  The standard way is to link and embed objects with the Insert Object dialog box, but there are other ways as well. The Paste, Paste Special, and Paste Link commands can all create OLE objects from data on the Clipboard. You can also link or embed objects by dragging them from one application and dropping them on another.


Glossary of OLE terms

The definitions in this list explain common terms in OLE programming. Read it for an introduction to important programming topics, or refer to it for clarification as you read other ObjectComponents chapters.

The definitions of advanced concepts assume you already know something about OLE and its standard interfaces. For more information about OLE, refer to the three OLE online Help files.

A

Activate

Aggregation

Automated Object

Automated Application

Automation

Automation Controller

Automation Server

B

BOCOLE Support Library

C

COM Object

Compound Document

Compound File

Connector Object

OCX Container

OLE Container

D

DLL Server

Document

E

Embedded Object

EXE Server

G

GUID

I

IDispatch Interface

In place Editing

Inprocess Server

Interface

IUnknown Interface

L

Linked Object

Link Source

Localization

O

ObjectComponents Framework

ObjectWindows Library

OLE

OLE Interface

Open Editing

P

Part

R

Reference Counting

Registrar Object

Registration Database

Registration Table

Remote View

S

Select

Server

System Registration Database

T

Type Library

V

Verb

View


Activate (definition)
Activate

The user activates a linked or embedded object by double-clicking it. Activating an object causes the server to execute the object's primary verb. For document-style objects, the primary verb is generally initiates an editing session, either in-place or open. For other objects, such as movies and sounds, the primary verb is usually Play. Activating is not the same as selecting; see the entry for Select.


Aggregation (definition)
Aggregation

A way of combining several OLE objects to make them function as a single bigger object. Objects are aggregated at run time. You can aggregate with objects that you did not design. An object aggregates to delegate commands or to inherit and override the functionality of other objects.

Aggregation is an advanced programming technique. In order for aggregated objects to act as a unit, all the aggregated objects must delegate any QueryInterface call they receive to the primary object, usually called the outer object. The outer object begins an aggregation by passing its own IUnknown pointer. The second object remembers the outer IUnknown pointer and routes all requests for an interface to the outer object. If the outer object does not support a requested interface, it forwards the request to the first in what might be a chain of aggregated objects. A client can reach all the interfaces supported by any of the auxiliary objects through the IUnknown of the outer object.


Automated Object (definition)
Automated Object

An OLE object that publishes commands other applications can send it. An automation server creates automated objects. The automated object can be the application itself or something that the application creates.


Automated Application (definition)
Automated Application

An OLE object that publishes commands other applications can send it. An automation server creates automated objects. The automated object can be the application itself or something that the application creates.


Automation (definition)
Automation

The ability of an application to define a set of commands for other applications to invoke.


Automation Controller (definition)
Automation Controller

An application that invokes commands to control automated objects or applications. A controller is sometimes called an automation client.


Automation Server (definition)
Automation Server

An application that exposes some of its own internal function calls as a set of commands that other programs can invoke. An automation object is what the server creates for other programs to control.


BOCOLE Support Library (definition)
BOCOLE Support Library

A DLL of OLE implementation utility interfaces that ObjectComponents calls internally. The support library implements a number of custom OLE interfaces designed by Borland. The BOCOLE.DLL file should be distributed with any ObjectComponents program. Its custom interfaces are considered internal and so are not documented. The source code for the BOCOLE support library, however, is included with Borland C++.


COM Object (definition)
COM Object

An object whose architecture conforms to the Component Object Model, a Microsoft specification that forms the basis of the OLE system. Briefly stated, the characteristics of COM objects are

They communicate through predefined interfaces.

They all support the IUnknown interface, and IUnknown includes the QueryInterface method for getting other optional interfaces.

They keep a reference count of their clients and delete themselves if the count reaches zero.

Only COM objects can communicate with OLE. Some of the classes in ObjectComponents are COM objects (see Connector object). ObjectComponents shields you from the details of interface methods, interface pointers, and reference counters. It connects you to OLE using familiar C++ and Windows programming models such as inheritance and messages.


Compound Document (definition)
Compound Document

A document that contains OLE objects brought in from other applications. A compound document might contain pieces of information from a spreadsheet, a database, and a word processor, all in one document that the user loads or saves with a single command. The objects from other applications are either linked or embedded in the container's document.


Compound File (definition)
Compound File

A single disk file that the operating system divides into independent compartments called storages. In effect, each storage has its own file I/O pointer so you can read, write, rewrite, and erase data in any one storage without needing to maintain offsets to other storages in the same file. Compound files are useful for storing compound documents because you can create a new storage for each linked or embedded object. OLE extends the file system by implementing interfaces to support compound files.


Connector Object (definition)
Connector Object

An ObjectComponents class that communicates with OLE for you. Connector objects connect parts of your application to OLE. TOcApp, for example, performs OLE functions for the application. TOcView performs OLE functions for one view of a document. TOcPart performs OLE functions for a linked or embedded object. The connector objects are partners that work together with corresponding parts of your application. You call their methods and they send you messages. Connectors are Component Object Model objects and implement COM interfaces. (Not all ObjectComponents classes are connectors.)


Container (definition)
Container

An application that permits OLE to embed or link objects from other applications into its own documents. Containers are also called clients of the servers that give them objects.


OCX Container (definition)
OCX Container

An application that permits OLE to embed or link OCX controls in its documents. OCX controls are OLE objects that conform to the Microsoft OCX specification.


DLL Server (definition)
DLL Server

A server whose code is in a dynamic-link library rather than an executable file. The advantage of a DLL server is speed. When OLE invokes an .EXE server to support an embedded object, it has to create a a separate process and marshall data to pass it between the two applications. A DLL, on the other hand, is part of the same system task as its client, so OLE calls from a container to a DLL server run much more quickly. See "Making a DLL server" on page 374.


Document (definition)
Document

This word has two different meanings for programmers. First, a document is a set of data that an application loads in response to File|Open. A document can be a spreadsheet, or a bitmap, or a letter, or any other set of data that an application treats as a whole.

Sometimes it is useful to distinguish between the data in a document and the appearance of the data onscreen. A spreadsheet, for example, might be able to display a single set of data as either a table of numbers or a chart. One document can be displayed different ways. In such cases, document refers only to the data, and each possible representation of the document is called a view.

ObjectWindows programmers are familiar with an application architecture called the Doc/View model that separates the code for managing document data from the code for displaying the data. ObjectComponents also has a document class and view classes, but they are not part of the ObjectWindows Doc/View model. The document class keeps track of the objects embedded in a document and the view classes draw the objects onscreen.


Embedded Object (definition)
Embedded Object

Data from a server application deposited by OLE in a container's document. OLE lets the user paste, drag, or insert objects into a container. If during these actions the user chooses to create an embedded object, then all the data in the object is copied to the container's document. When the user loads or saves the document, the data for the embedded object is written to the file along with the container's own native data.

Contrast embedded objects with linked objects, where the the data for the OLE object is stored in another application and the container receives only a reference to the object's file.


EXE Server (definition)
EXE Server

A server application compiled and linked into an executable file. A server can also be built as a library; see DLL server.


GUID (definition)
GUID

Globally unique identifier, a 16-byte value. OLE uses GUIDs to identify applications, the objects they produce, and the interfaces that objects implement. For linking and embedding, OLE needs GUIDs to match embedded objects to their servers even after the user transfers a compound document from system to system. If two servers had the same ID, OLE might accidentally invoke the wrong one. Each server and object type must have an absolutely unique ID. Tools such as GUIDGEN create the ID for you. For more information, see the clsid entry in the ObjectWindows Reference Guide.


IDispatch interface (definition)
IDispatch Interface

The OLE interface that all automated objects implement. With the four methods of the IDispatch interface, you can ask any automated object for information about its automated commands, look up the identifiers for particular commands, or invoke any command. For more information, see the OLEAUTO.HLP Help file.


In-place Editing (definition)
In-place Editing

Editing an OLE object in the container's window. During in-place editing, the container lets the server display its own menus and tool bars in the container's window. The purpose of in-place editing is to let the user edit any object in a document without leaving the document's window. Contrast Open editing.


In-process Server (definition)
In-process Server

A server whose code is in a dynamic-link library rather than an executable file. The advantage of a DLL server is speed. When OLE invokes an .EXE server to support an embedded object, it has to create a a separate process and marshall data to pass it between the two applications. A DLL, on the other hand, is part of the same system task as its client, so OLE calls from a container to a DLL server run much more quickly.


Interface (definition)
Interface

A set of function prototypes, usually declared as an abstract base class. OLE objects are able to communicate with each other because they implement standard interfaces, sets of functions that the system defines. The system defines only what functions an interface contains; it does not implement the functions. Each object implements the functions for itself. The interfaces are defined in the OLE system headers such as compobj.h and ole2.h. The OLE system communicates with applications and objects by calling the functions it assumes each one has implemented. For more about the OLE interface model, see the entry for Component Object Model (COM). For examples of standard OLE interfaces, see IDispatch and IUnknown.

Besides the standard interfaces, an object can define and implement its own custom interfaces. Of course the system can't call functions from custom interfaces because it doesn't know they exist, but other applications that know about the custom interface can use it. Internally, ObjectComponents works through a set of Borland custom interfaces. See BOCOLE support library.

ObjectComponents shields you from having to understand or implement particular interfaces. Advanced users who want to manipulate interfaces directly or mix in their own custom interfaces are free to do so.


IUnknown Interface (definition)
IUnknown Interface

The root interface that all OLE objects and interfaces must implement. With the three methods of the IUnknown interface, you can ask any object for a pointer to another interface it might also support, and you can adjust the object's reference count. For more information, see the Help file, OLE.HLP.


Linked object (definition)
Linked Object

An object that appears in a container document but whose data really resides in another file. When dragging or pasting an object into a container, the user can choose to create a link to the object instead of embedding it. The container does not receive or store the linked object's data in its own document. Instead, it receives only a string identifying the location of the actual data, which can be in a file.

Several containers can link to the same object. In that case, all the containers receive the same string pointing to the same object. If the data in the original object changes, then the changes are reflected automatically in all the documents that link to it. If the user embeds one object in several containers, then each container has its own copy of the object's data and changes in one copy do not affect the other copies.


Link Source (definition)
Link Source

The document that a link refers to, the source for the data in a linked object. Usually the link source is a server document, but it is not uncommon for containers to export link source data so that other applications can link to objects embedded or linked in the container's document. For information on becoming a link source.

.


Localization (definition)
Localization

Adapting an application to display strings in the user's language, whatever that might be. OLE servers need to speak the language of their client programs. If an automation server is marketed in several countries, it needs to recognize commands sent in each different language. A linking and embedding server registers strings that describe its objects to the user, and those too should be available in multiple languages in order to accommodate whatever language the user might request. ObjectComponents lets you place translations for all your strings in your resource file as XLAT resources. ObjectComponents chooses the right string at the right time.


ObjectComponents Framework (definition)
ObjectComponents Framework

A set of C++ classes from Borland International that encapsulate linking and embedding functions as well as automation functions. Internally the ObjectComponents classes implement standard and custom OLE interfaces. With ObjectComponents you write for OLE using familiar programming models such as inheritance and window messages instead of implementing COM interfaces.


ObjectWindows Library (definition)
ObjectWindows Library

A set of C++ classes from Borland International that encapsulate standard Windows programming functions such as managing windows and dialog boxes. The current version of ObjectWindows introduces some new classes, such as TOleWindow and TOleView, that use ObjectComponents classes to acquire OLE capabilities. The new classes make it very easy to add OLE support to existing ObjectWindows applications.


OLE (definition)
OLE

Object linking and embedding, an extension to the Windows system. (In newer versions of Windows, OLE is an integral part of the system, not an extension.) the new commands that OLE implements and the interfaces it defines add many new features to the system, including linking and embedding, automation, and compound file I/O.


OLE Interface (definition)
OLE Interface

A set of function prototypes, usually declared as an abstract base class. OLE objects are able to communicate with each other because they implement standard interfaces, sets of functions that the system defines. The system defines only what functions an interface contains; it does not implement the functions. Each object implements the functions for itself. The interfaces are defined in the OLE system headers such as compobj.h and ole2.h. The OLE system communicates with applications and objects by calling the functions it assumes each one has implemented. For more about the OLE interface model, see the entry for Component Object Model (COM). For examples of standard OLE interfaces, see IDispatch and IUnknown.

Besides the standard interfaces, an object can define and implement its own custom interfaces. Of course the system can't call functions from custom interfaces because it doesn't know they exist, but other applications that know about the custom interface can use it. Internally, ObjectComponents works through a set of Borland custom interfaces. See BOCOLE support library.

ObjectComponents shields you from having to understand or implement particular interfaces. Advanced users who want to manipulate interfaces directly or mix in their own custom interfaces are free to do so.


Open Editing (definition)
Open Editing

Editing an OLE object in the server's own window. Open editing happens when the user executes the Open verb. During open editing, the server's window opens up in front of the container's window. When the user finishes editing the object, the server window disappears and the modifications become visible back in the container window. Contrast In-place editing.


Part (definition)
Part

An object linked or embedded in a compound document. An ObjectComponents container creates an object of class TOcPart to represent each object linked or embedded in its document.

Part is the container's word for an object created by a server. In the server's code, the same object is created as a normal server document. ObjectComponents presents the document to OLE as an OLE object. The container, when it receives the OLE object, creates a TOcPart. When the part needs to be painted, the part object communicates through OLE with the server's view object.


Reference Counting (definition)
Reference Counting

Away of remembering how many clients an object has. Every section of code that requires the object to exist calls the object's AddRef method to increment the reference count. When the client code is done, it calls the object's Release method to decrement the reference count. If a Release call causes the count to reach 0, then the object is allowed to destroy itself.

Every OLE object has AddRef and Release methods because they are part of the IUnknown interface. Knowing who is a client and when to call AddRef or Release is sometimes complicated. ObjectComponents manages reference counting for you. Only advanced users will find any need to call AddRef or Release directly.


Registrar Object (definition)
Registrar Object

An object of type TRegistrar or TOcRegistrar. Every ObjectComponents application needs a registrar object. The registrar processes the application's command line, sets running mode flags, verifies the application's entries in the system registration database, and calls the application's factory function to launch the application.

Registration: giving information about the application to the system. OLE programs perform two different kinds of registration. When an application is first installed, ObjectComponents writes information from the application's registration tables into the system registration database. This information is static and needs to be recorded only once. The registrar object performs this task.

Subsequently whenever the user launches the application, ObjectComponents tells OLE that the application is running and it registers a factory for each type of document the application can produce. When the application ends, ObjectComponents unregisters the factories. The TOcApp or TRegistrar object performs this task.


Registration Database (definition)
Registration Database

A structured repository of information about applications installed on a particular computer. In 16-bit Windows, the database is kept in the REG.DAT file. In 32-bit Windows, the database is called the system registry and resides in private system files. Applications record their information during installation. The information includes identifiers for the application and its documents, descriptions of the application and its documents, the path to the application file, the default extension of the application's document files, and other details that help the OLE system associate servers with their objects.


Registration Table (definition)
Registration Table

A table built with registration macros and containing information about an application or about the types of documents an application creates. The macros create a structure of type TRegList. The registrar object reads the registration structure and copies any necessary information to the system registration database.


Remote View (definition)
Remote View

The view of its own object a server draws in a container's window. When an ObjectComponents server is launched to manage an object linked or embedded in a container's document, the server creates a TOcRemView object and a TOcDocument object. The view object draws in the container's window. The document object loads and saves the object's data.


Select (definition)
Select

The user selects an object by clicking it once. The selected object does not become active and cannot be edited. Conventionally a container indicates that an object is selected by drawing a rectangle with grapples around the object. (Grapples are small handles for moving the rectangle.) the container might permit the user to select several objects at once to move or delete as a group, but usually only one object per child window can be active at a time.


Server (definition)
Server

An application that creates objects for other applications to use. In this documentation, server usually refers to either a linking and embedding server or an automation server. A linking and embedding server creates data objects that containers can paste, drop, or insert into their own compound documents. An automation server creates objects that other applications can manipulate by sending commands for the object to execute. (A single application can choose to create both kinds of objects. It is even possible to link and embed automated objects.)


System Registration Database (definition)
System Registration Database

A structured repository of information about applications installed on a particular computer. In 16-bit Windows, the database is kept in the REG.DAT file. In 32-bit Windows, the database is called the system registry and resides in private system files. Applications record their information during installation. The information includes identifiers for the application and its documents, descriptions of the application and its documents, the path to the application file, the default extension of the application's document files, and other details that help the OLE system associate servers with their objects.


Type Library (definition)
Type Library

A file describing the commands an automation controller supports. Creating a type library is the standard way for an automation server to publish the programming interface it implements. The type library tells what objects the server creates and describes the objects' properties and methods. Type information is read by compilers and interpreters that process automation commands. Some applications also allow the user to browse the type information.

Any ObjectComponents automation server generates a type library if you invoke it with the -TypeLib command line switch. Type libraries conventionally use the .TLB or .OLB extension. An automation server registers the location of its type library during installation.


Verb (definition)
Verb

A command that a linking and embedding server can execute with its objects. The server tells the container what verbs it supports and the container displays the verb strings on its own Edit menu. To execute a verb, the user selects an object and then chooses a verb from the menu. The container updates the verb menu each time the user selects a new object.

The server can support any verbs it chooses. Most servers support the Edit and Open verbs for in-place or open editing. Depending on the kind of data it owns, a server might choose to offer other verbs such as Play and Rewind.


View (definition)
View

The graphical representation of data. The term is used to distinguish between the way the data is painted and the data itself, usually called the document. A single word processor document, for example, might have three different views: a page layout view, a draft view without fancy fonts, and a print preview view.

In ObjectComponents, containers create views to draw their compound documents. Servers also create views to draw the objects they create. Both create a TOcDocument object to manage the data and a view object, either TOcView or TOcRemView, to draw the document.

In ObjectWindows, Doc/View refers to a particular application architecture supported by the framework that also treats data and its representation in separate classes.


ObjectComponents Libraries

See also

An ObjectComponents application links to an OCFxxxx library and to the OLE2W16 library.

Library	Description

OCFWI.LIB	For use with the dynamic library versions of the RTL and class libraries

OCFWIU.LIB	For use in a user DLL with the dynamic library versions of the RTL and class libraries

OCFWL.LIB	Large model

OCFWLU.LIB	Large model for use in a user DLL

OCFWM.LIB	Medium model ObjectComponents

OLE2W16.LIB	Import library for OLE system DLLs


ObjectComponents Header Files

Header files, located in your INCLUDE/OCF subdirectory, contain declarations for class functions and definitions for data types and constants.

File	Contents

appdesc.h	TAppDescriptor, TComponentFactory

autodefs.h	Classes and structs used for automation

automacr.h	Macros for automation declarations and definitions

ocapp.h	OC_APPxxxx messages, TOcApp, TOcFormatName, TOcMenuDescr, TOcAppHost, TOcAppFrameHost, TOcAppFrameHostMsg, TOcNameList, TOcRegistrar, WM_OCEVENT message

ocapp.rh	IDS_CFxxxx resource IDs for strings describing standard Windows clipboard formats

occtrl.h	TOcControl, TOcControlEvent, TOcxView,

ocdefs.h	TXObjComp, HR_xxxx Return constants, declaration specifiers

ocdoc.h	TOcDocument

ocfevx.h	Message cracker macros for WM_OCEVENT

ocfpch.h	#include statements for all ObjectComponents headers, used with pre-compiled headers

ocobject.h	TOcAspect, TOcDialogHelp, TOcDropAction, TOcInitHow, TOcInitInfo, TOcInitWhere, TOcInvalidate, TOcPartName, TOcScrollDir

ocpart.h	TOcPart, TOcPartCollection, TOcPartCollectionIter, TOcVerb

ocreg.h	OCxxxx global functions, ocrxxxx registration constants,  TRegistrar, TXRegistry

ocremvie.h	TOcRemView

ocstorag.h	TOcStream, TOcStorage

ocview.h	OC_VIEWxxxx, OC_CTRLEVENTxxxx, OC_AMBIENT_GETxxxx, OC_AMBIENT_SETxxxx, and OC_USEREVENT messages, TOcDragDrop, TOcFormat, TOcFormatList, TOcFormatListIter, TOcSaveLoad, TOcScaleFactor, TOcToolBarInfo, TOcView, TOcViewPaint, TOcContainerHost, TOcServerHost, TOcContainerHostMsg, TOcServerHostMsg

oleutil.h	DECLARE_COMBASES# macros, TOleAllocator, TUnknown, TXOle


General OLE classes, macros, and typedefs
General OLE classes, macros, and type definitions

Description

ObjectComponents provides the following utility items for use in building OLE applications, whether they support linking and embedding or automation.

Item	Meaning

HR_xxxx macros	Return values from OLE functions

_ICLASS macro	Specifier for declaring a class that implements an OLE interface

_IFUNC macro	Specifier for declaring OLE functions

_OCFxxxx macros	Specifiers for declaring ObjectComponents classes

TComponentFactory typedef	Callback function where an application creates objects that OLE requests

TLocaleId typedef	Data type for language setting identifiers

TOleAllocator class	Establishes a memory allocator for OLE to use

TUnknown class	Implements the fundamental IUnknown interface required of all OLE objects


Global Utility Functions

The items in this table are utility functions that ObjectComponents declares globally.

Item	Purpose

DynamicCast	Converts a pointer from one type to another if both types are related through inheritance

MostDerived	Returns a pointer to the most derived class type that fits a given object

OcRegisterClass	Writes all the information from one registration table to an output stream

OcRegistryUpdate	Merges all the information from an input stream into the registration database

OcRegistryValidate	Checks whether information in a registration table matches the corresponding information already recorded in the registration database

OcSetupDebugReg	Takes the information from a registration table and writes to an output stream the registration entries for a debugging version

OcUnregisterClass	Removes entries from the system's registration database


ObjectComponents exception classes

See also

ObjectComponents throws the types of exceptions shown in this list. All the exception classes derive from TXBase.

Class	Purpose

TXAuto 	Exceptions that occur during automation

TXObjComp	Exceptions that occur during ObjectComponents linking and embedding operations

TXOle	Exceptions that occur while processing OLE API commands

TXRegistry	Exceptions that occur while using the system registration database


Automation classes

See also	Overview

ObjectComponents provides the following classes that support automation.

TAutoBase	Base class for deriving automated objects

TAutoCommand	Holds all the data for one command received by an automation server

TAutoEnumerator<>	Lets an automation controller enumerate items in a server's collection

TAutoIterator	Lets an automation server iterate items in an automated collection

TAutoObject<>	Creates a smart pointer to an automated object

TAutoObjectByVal<>	Lets an automation server automate a method that returns an object by value (not by reference)

TAutoObjectDelete	Lets an automation server automate a method that returns an object

TAutoProxy	Base class for deriving the C++ objects an automation controller creates to represent the OLE objects it wants to control

TAutoStack	Holds a set of TAutoCommand objects each representing a command received by an automation server

TAutoVal	Holds the data from a VARIANT union, the data format OLE uses for sending automation commands

TRegistrar	Manages system registration tasks for an automation application


Automation classes, Enumerated Types, and Type Definitions
Automation Enumerated Types and Type Definitions

See also

ObjectComponents provides the following items that support automation.

AutoDataType enum	Identifiers for automation data types

AutoSymFlag enum	Flags that describe attributes of an automation command

ObjectPtr typedef	void pointer to a C++ object


Automation Data Types

See also	Declarations and Definitions

ObjectComponents provides the following data types that support automation. To use these data types, see Declarations and Definitions.

TAutoBool struct

TAutoCurrency struct

TAutoCurrencyRef struct

TAutoDate struct

TAutoDateRef struct

TAutoDouble struct

TAutoDoubleRef struct

TAutoFloat struct

TAutoFloatRef struct

TAutoInt typedef

TAutoLong struct

TAutoLongRef struct

TAutoShort struct

TAutoShortRef struct

TAutoString struct

TAutoVoid struct


Declarations and Definitions of Automation Data Types

See also

An automation data type is a structure that exists solely to describe a single type of data. Automation definitions use these structures to assist in converting parameters and return values between the VARIANT unions that OLE uses and the C++ data types that your programs use.

For the most part, although they are structures, you cannot create instances of them because they lack constructors and contain only a single static member. They all derive from TAutoType and inherit its GetType method. The only thing most of these structures do is respond to GetType calls by returning the static ID for a data type.

Header File

ocf/autodefs.h

Description

The following table lists C++ data types that might appear in your programs and the corresponding data types that you should use in automation declarations (DECLARE_AUTOCLASS) and definitions (DEFINE_AUTOCLASS).

In the left column, find a type that your automated class uses in its arguments or its return values. The other columns tell what data type to specify in the corresponding entries of the automation declaration and definition.

C++ Type	Declaration Type	Definition Type

 	(DECLARE_AUTOCLASS)	(DEFINE_AUTOCLASS)

short	short	TAutoShort

unsigned short	short or unsigned	TAutoShort or TAutoLong

long	long	TAutoLong

unsigned long	unsigned long	TAutoLong (treated as signed long)

int	int	TAutoInt

unsigned int	int or long	TAutoInt or TAutoLong

float	float	TAutoFloat

double	double	TAutoDouble

bool (or int)	TBool	TAutoBool

TAutoDate	TAutoDate	TAutoDate

TAutoCurrency	TAutoCurrency	TAutoCurrency

char*	TAutoString	TAutoString

const char*	TAutoString	TAutoString

char far*	TAutoString	TAutoString

const char far*	TAutoString	TAutoString

string	string	TAutoString

enum	short or int	TAutoShort, TAutoInt, or user-defined AUTOENUM

T*	TAutoObject<>	T (class T must be automated)

T&	TAutoObject<>	T (class T must be automated)

const T*	TAutoObject<>	T (class T must be automated)

const T&	TAutoObject<>	T (class T must be automated)

T* (returned)	TAutoObjectDelete<>	(C++ object deleted when no refs)

T& (returned)	TAutoObjectDelete<>	(C++ object deleted when no refs)

T (returned)	TAutoObjectByVal<>	T (T copied, deleted when no refs)

void (no return)	(use AUTOFUNCnV macros)	TAutoVoid

short far*	short far*	TAutoShortRef

long far*	long far*	TAutoLongRef

float far*	float far*	TAutoFloatRef

double far*	double far*	TAutoDoubleRef

TAutoDate far*	TAutoDate far*	TAutoDateRef

TAutoCurrency far*	TAutoCurrency far*	TAutoCurrencyRef


Automation Declaration Macros

See also

Header File

ocf/automacr.h

Description

To make parts of an automated class accessible to OLE, an automation server adds declaration macros to the declaration of the C++ class and definition macros to the implementation of the C++ class. The declaration macros create command objects for executing commands sent by the controller.

The block of automation declaration macros always begins with DECLARE_AUTOCLASS or DECLARE_AUTOAGGREGATE macro. There is no need for a matching END macro to close the declaration.

Macro	Meaning

DECLARE_AUTOCLASS(cls)	The macros that follow declare automatable members of the user-defined class cls.

DECLARE_AUTOAGGREGATE(cls)	The macros that follow declare automatable members of a class that is, inherits from, or delegates to a COM object.

Declaration Macros

After DECLARE_AUTOCLASS comes a series of macros, one for each class member that you choose to expose. Which particular macros you choose depends on what the members are.

Declaration Macro	Member

AUTODATA	Data

AUTOFLAG	A bit flag

AUTOFUNC	Function

AUTOITERATOR	Iterator object

AUTOPROP	Property

AUTOPROXY	Property containing an automated object

AUTOSTAT	Static member or global function

AUTOTHIS	*this

AUTODETACH macro

In addition, an automation declaration can also include the AUTODETACH Macro. This macro does not expose a class member. It invalidates external references when the object is destroyed.


Automation Definition Macros

See also

Header File

ocf/automacr.h

Description

To make parts of an automated class accessible to OLE, an automation server adds declaration macros to the declaration of the C++ class and definition macros to the implementation of the C++ class.

The block of automation definition macros begins with DEFINE_AUTOCLASS and ends with END_AUTOCLASS, unless the object is, inherits from, or delegates to a Component Object Model (COM) object. In that case, the block of automation definition macros begins with DEFINE_AUTOAGGREGATE and ends with END_AUTOAGGREGATE.

Macro	Meaning

DEFINE_AUTOCLASS(cls)	The macros that follow define automatable members of the user-defined class cls.

END_AUTOCLASS(cls, name, doc, help)	The C++ class cls is exposed to OLE controllers under the name name. If the user asks OLE about the object name, the system returns the string in doc. If a .HLP file is registered for the object, then the context ID in help points to a screen that describes the object.

DEFINE_AUTOAGGREGATE(cls, aggregator)	The macros that follow define automatable members of the user-defined class cls, which is, inherits from, or delegates to a COM object.

END_AUTOAGGREGATE(cls, name, doc, help)	Same as END_AUTOCLASS.

Between the DEFINE and END macros comes a series of other macros describing each exposed data member or function. The macros implement methods for a class nested within your automated class. When ObjectComponents receives commands from a controller, it passes them to the nested class. The macros build wrapper functions in the nested class that enable it to call your own class directly.

Which particular macros you choose depends on what the members are.

Member	Declaration Macro

Automated application	EXPOSE_APPLICATION Macro

Auxiliary class	EXPOSE_DELEGATE Macro

Base class	EXPOSE_INHERIT Macro

Collection iterator	EXPOSE_ITERATOR Macro

Method	EXPOSE_METHOD Macros

Read-only property	EXPOSE_PROPRO

Read-write property	EXPOSE_PROPRW

Write-only property	EXPOSE_PROPWO

Shutdown method	EXPOSE_QUIT


Automation Hook Macros

See also

Header File

ocf/automacr.h

Description

These macros establish hooks to be invoked every time a particular automation command is executed. They are never used by themselves but always as the last parameter of some other automation declaration macro. If you add one of these hooks to the declaration of some exposed class member, then every time an automation controller attempts to execute that command, ObjectComponents first executes the code in the hook. The code can be a simple expression or it can contain calls to other functions.

Most of the macros expect to receive some expression or code as a parameter. Often the code or expression in the macro needs to refer to the arguments passed in or to the value of an automated data member. Within the macro expression, write Arg1, Arg2, Arg3... to refer to the received arguments. Write Val to refer to an automated data member.

Macro	Meaning

AUTONOHOOK	Use this macro, without arguments, to prevent anyone from hooking the command. Not even ObjectComponents can monitor the call. (For advanced uses only.)

AUTOINVOKE(code)	The code here is executed each time the automation command is executed. Create an AUTOINVOKE hook if you want to override the normal execution sequence.

AUTORECORD(code)	The code inserted here creates a record of the commands executed so that the sequence can be stored and replayed.

AUTOREPORT(code)	The code inserted here returns an error code from the automated member. If code evaluates to 0, OLE assumes the command succeeded. If code evaluates to a nonzero value, then OLE throws an exception that returns an error code to the controller.

Within the code expression, use Val to refer to the actual value returned.

AUTOUNDO(code)	The code inserted here creates a TAutoCommand object that will undo the action of the current command.

AUTOVALIDATE(condition)	The code here should evaluate to true if the arguments received are valid for the command and false otherwise. If the expression returns false, OLE throws an exception that returns an error code to the controller application.

Example

This declaration ensures that an automated data member is never assigned a value outside a given range.

AUTODATA(Number, Number, short,

 AUTOVALIDATE(Val>=NUM_MIN && NotTooBig(Val)));


Automation Proxy Macros

Header File

ocf/automacr.h

Description

An automation controller creates a proxy object (derived from TAutoProxy) to represent an automated OLE object. For every command the controller wants to send the object, it adds a method to the proxy object. The proxy methods mimic the commands the object supports. When the controller calls proxy methods, ObjectComponents sends automation commands through OLE.

The implementation of a proxy method always contains three macros: an AUTONAMES macro, an AUTOARGS macro, and an AUTOCALL macro. AUTONAMES associates names with arguments. AUTOARGS describes any arguments that do not have names. The use of names makes it possible to send partial sets of arguments and let the server assign default values to the remaining arguments.

The third macro, AUTOCALL, tells whether the command represents a method or a property of the automated object and whether the command returns a value.

To generate proxy object declarations and definitions directly, use the TYPEREAD.EXE tool (located in the OCTOOLS subdirectory.) TYPEREAD scans the type library of an automation server and generates complete proxy code for controlling the server.

You are free to subsititute your own code for the standard macros in order to handle special situations.

Macro	Description

AUTONAMES	Associates names with arguments so the caller can choose to pass only selected arguments

AUTOARGS	Describes arguments that do not have names

AUTOCALL	Tells whether the command is a method or a property and whether it returns a value


Registration Keys

See also

Most ObjectComponents programs build registration tables describing their OLE capabilities. (Only automation controllers can omit this step.) The registration tables contain keys paired with values. The keys are standard. You decide which ones to register and you supply values for them.

Which keys you choose depends on whether your application is a server, a container, or an automation program. Some keys must be registered and some are optional. Furthermore, some apply only to the application's primary registration table, and others apply to the tables for each of the application's document types.

A registration table starts with the BEGIN_REGISTRATION macro and ends with END_REGISTRATION. In between is one macro for each key you want to register. The macro depends on the key. Most keys use the REGDATA, but there are others such as REGFORMAT and REGSTATUS. For more information, see Registration Macros in OWL.HLP.

If your application is a server, most of the information in its registration tables is recorded in the system's registration database. Putting the information there makes it possible for OLE to learn much about the server without actually loading the application into memory. For example, if an automation controller asks for information about the commands an automation server supports, OLE can locate the server's type library from an entry in the database.

Key	Meaning

appname	A short name for the application.

aspectall	Option flags that apply to all presentation aspects.

aspectcontent	Option flags for the content view of an object.

aspectdocprint	Option flags for the printed document view of an object.

aspecticon	Option flags for the iconic view of an object.

aspectthumbnail	Option flags for the thumbnail view of an object.

clsid	A GUID identifying the application.

cmdline	Arguments OLE should place on the command line when it launches the server.

debugclsid	A GUID identifying the debugging version of a server. This is always generated internally. You should never specify it directly.

debugdesc	A long string describing the debugging version of a program.

debugger	The file name and command line switches for loading your debugger.

debugprogid	A string naming the debugging version of a program. Defining this forces ObjectComponents to register debugging and non-debugging versions.

description	A string describing the application.

directory	The default directory for browsing document files.

docfilter	File specification for listing files created by the application.

docflags	Option flags for the application's documents.

extension	A three-letter file-name extension for files created by the server.

filefmt	Name of default file format.

formatn	A Clipboard format the application supports. (Use REGFORMAT to register Clipboard formats.)

handler 	A full path pointing to a library that can draw objects created by the server. Defaults to OLE2.DLL.

helpdir	Full directory where online Help for the type library resides.

iconindex	An index telling which of the icons in the server's resources represents the type of objects the server produces. (Use REGICON to register an icon.)

insertable	Indicates that the application serves its document for linking and embedding in container documents.

language	Locale ID currently in effect. (Set internally during automation.)

menuname	A short name for the server, used in a container's menu.

path	The path where OLE looks to find the server. This key is set internally during registration.

permid	A string that names the application without indicating any version.

permname	A string that describes the application without indicating any version.

progid	A string uniquely naming the application.

typehelp	Name of the file where online Help for the type library resides.

usage	Indicates the whether the server can support concurrent clients with a single application instance.

verbn	A string naming an action the server can perform with its objects.

verbnopt	Option flags describing the server's verbs. (Use REGVERBOPT to register verb options.)

version	Version string for the application and type library.


Automation struct

See also

TAutoType


Linking and embedding classes

SeeAlso	Overview

ObjectComponents provides the following classes for use by applications that support linking and embedding.

TOcApp	Connector object that implements BOCOLE interfaces for the application

TOcAppFrameHost,	Contains virtual functions for each application message.

TOcAppFrameHostMsg,	Forwards application messages to the application window.

TOcContainerHost	Contains pure virtual functions for each container event.

TOcServerHost	Contains pure virtual functions for each server event.

TOcContainerHostMsg	Forwards container messages to the view window.

TOcServerHostMsg	Forwards server messages to the view window.

TOcControl	View object for a control.

TOcDataProvider	Provides support for serving a portion of a document

TOcDocument	Manages the parts in a container's compound document

TOcFormat	Holds information about a view's support for a particular Clipboard data format.

TOcFormatList	List of Clipboard data formats a document supports

TOcFormatListIter	Iterator for the list of Clipboard data formats a document supports

TOcFormatName	Holds strings describing a single data format that an application might encounter on the Clipboard (see TOcNameList)

TOcInitInfo	Holds information a container needs in order to place a new object in its document

TOcLinkView	A connector object that helps containers establish links to a server document

TOcAppHost	Base class for deriving OLE-enabled application objects

TOcNameList	Contains a collection of strings describing all the data formats that an application might find on the Clipboard

TOcPart	Connector object that a container uses to represent an object linked or embedded in one of its documents

TOcPartChangeInfo	Carries information to accompany an OC_VIEWPARTINVALID event

TOcPartCollection	Manages a collection of linked or embedded parts

TOcPartCollectionIter	Iterator for the collection of parts linked or embedded in a single document

TOcRegistrar	Manages OLE registration tasks for a linking and embedding application

TOcRemView	Connector object that a server uses to draw an object linked or embedded in a container's document

TOcScaleFactor	Carries information from a container to a server requesting that linked or embedded objects be drawn to a certain scale

TOcVerb	Holds information about an action that a server is able to perform with its own objects when they are linked or embedded in a container

TOcView	A connector object that an application uses to draw its own documents in its own frame window

TOcxView	A connector object that an application uses to draw its own controls in its own frame window

TOcViewCollection	Manages a set of link views associated with a document

TOcViewCollectionIter	Enumerates the views of a compound document


See Also

General OLE Classes, Macros, and typedefs

ObjectComponents Exception Classes

Registration Keys


Linking and Embedding Enums

ObjectComponents provides the following enumerated types for use by applications that support linking and embedding.

TOcAppMode	Flags identifying the application's running conditions

TOcAspect	Flags identifying object presentation aspects

TOcDialogHelp	Constants identifying standard OLE dialog boxes where a user can ask for help

TOcDropAction	Constants identifying actions that can result from dropping an object on a window

TOcMenuEnable	Flags that determine which OLE commands on the Edit menu should be enabled.

TOcInitHow	Constants identifying the action a container is to take on receiving a new object--either link or embed

TOcInitWhere	Constants identifying places the data for an object can reside

TOcInvalidate	Flags indicating whether an object is invalid because of a change in its data or just in its appearance

TOcPartName	Constants identifying different strings a container might request when asking for the name of an object linked or embedded in it

TOcScrollDir	Constants identifying directions a container might be asked to scroll its window


Linking and Embedding Messages

SeeAlso

ObjectComponents provides the following mesages for use by applications that support linking and embedding

OC_APPxxxx	Messages sent to an application object

OC_VIEWxxxx	Messages sent to a view object

OC_AMBIENT_GETxxxx, OC_AMBIENT_SETxxxx, and OC_CTRLEVENTxxxx	Messages sent from an OCX control to a container

WM_OCEVENT	Carries event signals from ObjectComponents to an application


See Also

Messages and Windows


Linking and Embedding Structs

ObjectComponents provides the following structs for use by applications that support linking and embedding.

TOcDragDrop	Holds information a container needs in order to receive an object dropped on its window

TOcFormatInfo	Holds information about one view's support for a particular Clipboard data format.

TOcMenuDescr	Holds information about a shared menu where the container and server merge their commands for in-place editing

TOcSaveLoad	Carries information an application needs to save or load a linked or embedded object

TOcToolbarInfo	Carries handles to a server's tool bars to be displayed in the container's window during in-place editing

TOcViewPaint	Carries information that tells a server how to repaint a linked or embedded object when the container invalidates part of the object's surface


ocrxxxx constants

See also

Header File

ocf/ocreg.h

Description

The ocreg.h header defines a number of constants used in constructing an application's registration tables. These constants all begin with ocr. They fall into several groups. Most of them are used with the REGFORMAT macro to describe the kinds of data transfers a document supports.

Group	Meaning

Aspect Constants	Data presentation modes (such as icon, content, or thumbnail)

Clipboard Constants	Clipboard data formats (such as text, bitmap, or link source)

Direction Constants	Data transfer directions (getting or setting)

Limit Constants	Maximum number of items that can be registered

Medium Constants	Data transfer mediums (such as disk file or Clipboard)

Object Status Constants	Aspect options (such as showing icon only or redrawing on resize)

Usage Constants	Support for multiple clients (single use or multiple use)

Verb Attributes constants	Verb option flags (never dirties and show on menu)

Verb Menu Flags	Verb display options (such as grayed, disabled, or menu bar break)


Compound File I/O classes

TOcStorage

TOcStream


Compound File I/O Enumerated Types and Structs

STATSTG

STGC enum


Overview of Linking and Embedding classes

See also

The following classes support linking and embedding, but if your program uses ObjectWindows you won't need to work directly with most of them.

Class	Description

TOcApp	Connects containers and servers to OLE. It implements COM interfaces for the application.

TOcDocument	Represents a compound document. It holds parts (embedded objects).

TOcAppHost	A mix-in class for deriving the application object in a linking and embedding program. It coordinates some basic housekeeping chores related to registration and memory management.

TOcPart	Represents an embedded or linked object in a document.

TOcRegistrar	Records application information in the system registration database and tells OLE when the application starts and stops. Also creates the TOcApp object and responds when OLE wants a server to make something.

TOcRemView	Represents a remote view for a server document. The server creates a remote view for every object it donates to a container. The remote view is drawn in the container's window.

TOcView	Responsible for displaying a part. A container needs a view for every part it embeds.

Although ObjectComponents includes classes for documents and views, it does not require applications to use the ObjectWindows Doc/View model. If you do use the Doc/View model, the new TOleDocument and TOleView classes make OLE programming even easier. ObjectWindows is not required, however. Any C++ program can use the ObjectComponents Framework.


Overview of automation classes

See also

Following are some ObjectComponents classes used for automation.

Class	Description

TAutoBase	Simplifies clean-up chores when an automated object is destroyed. Make it the base class for your automated classes if you want that help.

TAutoProxy	the base class for an automation controller's proxy objects. Controllers create C++ proxy objects to represent the OLE objects they want to manipulate. The proxy objects become connected to OLE when they derive from TAutoProxy.

TOleAllocator	Initializes the OLE libraries and, optionally, passes OLE a custom memory allocator for managing any memory the system allocates on the program's behalf.

TRegistrar	Records application information in the system registration database and tells OLE when the application starts and stops.

There are more automation classes than the above table shows, but many of them are internal to the ObjectComponents implementation. Most of the work in automating an existing application is done with macros. Automating a class means writing two tables of macros, one in the class declaration and one in the class implementation. The macros describe the methods you choose to expose. Within the parent class they create nested classes, one for each command. ObjectComponents knows how to make a nested object execute the method it exposes, and the nested class calls members of the parent class directly.

The connector objects that ObjectComponents creates to implement COM interfaces for an automation program are considered internal. ObjectComponents makes them for you when they are needed.


ObjectComponents Messages

See also

When ObjectComponents needs to tell an application about signals and events that come from OLE, it sends a message through the normal Windows message queues. The message it sends is WM_OCEVENT. The value in the message's wParam identifies a particular event. Only applications that support linking and embedding receive WM_OCEVENT messages. (They are sent by the application's TOcApp, TOcView, and TOcRemView objects. Automation applications that don't support linking and embedding have no need for any of these objects.)

Simple ObjectWindows applications don't need to process any of the events because the new OLE classes have default event handlers that make reasonable responses for you. To modify the default behavior, add event handlers to your ObjectWindows program. If you are programming without ObjectWindows, handle WM_OCEVENT in your window procedure.

The events are divided into two groups. Those that concern the application as a whole are listed in the following table. Those that call for a response from a particular document are addressed to the view window. They are listed in the next table.

Most of the events in the following tables are sent only to a server or to a container. A single application receives both kinds of messages if it chooses to support both container and server capabilities.

Application messages for TOcApp clients

wParam value	Recipient	Description

OC_APPDIALOGHELP	Container	Asks the container to show Help for one of the standard OLE dialog boxes where the user has just clicked the Help button.

OC_APPBORDERSPACEREQ	Container	Asks the container whether it can give the server border space in its frame window.

OC_APPBORDERSPACESET	Container	Asks the container to rearrange its client area windows to make room for server tools.

OC_APPFRAMERECT 	Container	Requests client area coordinates for the inner rectangle of the program's main window.

OC_APPINSMENUS 	Container	Asks the container to merge its menu into the server's.

OC_APPMENUS	Container	Asks the container to install the merged menu bar.

OC_APPPROCESSMSG 	Container	Asks the container to process accelerators and other messages from the server's message queue.

OC_APPRESTOREUI 	Container	Tells the container to restore its normal menu, window titles, and borders because in-place editing has ended.

OC_APPSHUTDOWN 	Server	Tells the server when its last embedded object closes down. If the server has nothing else to do, it can terminate.

OC_APPSTATUSTEXT 	Container	Passes text for the status bar from the server to the container.

A view is the image of an object as it appears onscreen. When an OLE server gives an object to a container, the object contains data. The server also provides a view of the data so OLE can draw the object onscreen. Sometimes the word view also refers to the window where the container draws a compound document with all its embedded parts. Each object has its own small view, and the container has a single larger view of the whole document with all its embedded objects.

View messages for TOcView and TOcRemView clients

wParam value	Recipient	Description

OC_VIEWATTACHWINDOW	Server	Asks server window to attach to its own frame window or container's window.

OC_VIEWBORDERSPACEREQ	Container	Asks whether server can have space for a tool bar within the view of an embedded object.

OC_VIEWBORDERSPACESET 	Container	Asks container to rearrange its windows so the server can show its tool bar within an embedded object.

OC_VIEWBREAKLINK	Server 	Asks server to break a link to the currently selected data.

OC_VIEWCLIPDATA 	Server	Asks server to provide clipboard data in a particular format.

OC_VIEWCLOSE 	Server	Asks server to close its document.

OC_VIEWDRAG 	Server	Asks server to provide visual feedback as the user drags its embedded object.

OC_VIEWDROP 	Container	Tells container an object has been dropped on its window and asks it to create a TOcPart.

OC_VIEWGETITEMNAME	Server	Asks the server for a moniker identifying the currently selected data.

OC_VIEWGETPALETTE 	Server	Asks server for the color palette it uses to draw an object.

OC_VIEWGETSCALE	Container	Asks container to give scaling information.

OC_VIEWGETSITERECT	Container	Asks container for the site rectangle that a part occupies.

OC_VIEWINSMENUS 	Server	Asks server to insert its menus in a composite menu bar.

OC_VIEWLOADPART 	Server	Asks server to load an embedded object stored in the container's data file.

OC_VIEWOPENDOC	Server	Asks server to open a document with the specified path.

OC_VIEWPAINT 	Server	Asks server to draw or redraw an object at a particular position in a given device context.

OC_VIEWPARTACTIVATE	Container	Indicates that an embedded part has become active.

OC_VIEWPARTINVALID 	Container	Indicates that embedded objects needs to be redrawn.

OC_VIEWPARTSIZE 	Server	Asks server the initial size of its view in pixels.

OC_VIEWSAVEPART 	Server	Asks server to write the data for an object into the container's file.

OC_VIEWSCROLL 	Container	Asks container to scroll its view window.

OC_VIEWSETSCALE	Server	Asks server to handle scaling.

OC_VIEWSETLINK	Server	Asks server to create a link to the currently selected data.

OC_VIEWSETSITERECT	Container	Asks container to set the site rectangle.

OC_VIEWSETTITLE	Container	Asks the container to add to its title bar the name of the server for the active object.

OC_VIEWSHOWTOOLS 	Server	Asks server to display its tool bar in container's window.

OC_VIEWTITLE 	Container	Asks container for the caption in its frame window.


Messages and Windows

See also

Because the view and part objects expect to send notification messages to a particular document, every ObjectComponents application is expected to create a new window for each open document. Document windows should not be frame windows; they should be client windows that exactly fill the client area of a parent frame window. In an SDI application, the parent is the application's main frame window. In an MDI application, the parent is an MDI child frame. ObjectWindows programs should use TOleWindow for client windows. Many ObjectWindows applications, including all those that use the Doc/View model, already possess client windows.


Exception Handling in ObjectComponents

See also

ObjectWindows 2.5 modifies the hierarchy of exception classes. TXBase is the new base class for all exception classes. TXOwl derives from it, as do the new exception classes summarized in the following table.

Class	Purpose

TXAuto 	Exceptions that occur during automation

TXObjComp	Exceptions that occur during ObjectComponents linking and embedding operations

TXOle	Exceptions that occur while processing OLE API commands

TXRegistry	Exceptions that occur while using the system registration database

Because the exception classes all derive from TXBase, a general-purpose catch statement often takes a TXBase& as a parameter. The catch statement in the following example receives any exception thrown by ObjectWindows or ObjectComponents:

int

OwlMain(int /*argc*/, char* /*argv*/ [])

{

  try {

    Registrar = new TOcRegistrar(AppReg, TOleFactory<TMyApp>(),

                                 TApplication::GetCmdLine());

    return Registrar->Run();

  }

  catch (TXBase& x) {

    ::MessageBox(0, x.why().c_str(), "Exception", MB_OK);

  }

  return -1;

}


TXOle and OLE Error Codes

See also

Most of the OLE API functions pass back a return value of type HRESULT (or the nearly identical SCODE). The return value indicates whether the call was successful, and it can also encode other status information. When a public member function of an ObjectComponents class results in a call to an OLE interface and the interface call fails, then ObjectComponents turns the OLE return result into a C++ exception object of type TXOle. This allows you to handle OLE error codes via the standard C++ try and catch constructs.

The TXOle class defines a variable, Stat, which holds the return value passed back from from a failed OLE API call. Therefore, a catch statement taking a TXOle& as a parameter has access to the OLE error code. The following code shows an example of a routine where the error value is simply returned back to the caller. This is useful if the function is called from an application that cannot handle C++ exceptions.

HRESULT

TMyAppDescriptor::CheckTypeLib(TLangId lang, const char far* file)

{

  HRESULT stat = HR_NOERROR;

  // Create OCF classes and invoke OCF methods to perform operation

  try {

    TOleCreateList typeList(new TTypeLibrary(*this, lang), file);

    .

.

.

  }

  catch(TXOle& x) {                    // Catch OLE exception

    stat = ResultFromScode(x.Stat);    // Create HRESULT from SCODE

  }

  return stat;                         // Return OLE error code

}

The previous example uses the ResultFromScode macro to cast an SCODE to an HRESULT. The OLE headers define various other macros that allow you to break down, assemble, and convert the various components of the value returned from an OLE API call.For more information, search for the topic "Error Handling Functions and Macros" in OLE.HLP.

If ObjectComponents catches a TXOle exception internally, it displays a dialog box showing the OLE return code. OLE documents the codes only in the header files where they are defined. To make what information there is more accessible, the DOCS/OLE_ERR.TXT file extracts information from that header and presents the codes in numerical order.


DynamicCast function

See also	Global Utility Functions

Header file

ocf/autodefs.h

Syntax

const void far* DynamicCast(const void far* obj, const typeinfo& src, const typeinfo& dst);

Description

Attempts to convert a pointer from one type to another. The attempt succeeds only if the old type and the new type are related through inheritance.

obj is the pointer you want to cast to a new type. src is type information about the source object. dst is information about the destination type.

If the conversion succeeds, DynamicCast returns a pointer to the new type. If it fails, the return is zero.

You can generate the src and dst parameters with the typeid parameter. (ObjectComponents requires the use of RTTI.)


MostDerived function

See also	Global Utility Functions

Header file

ocf/autodefs.h

Syntax

const void far* MostDerived(const void far* obj, const typeinfo& src);

Description

Returns a pointer to the most derived class type that fits the given object. This is useful when dealing with polymorphic objects. Use it to obtain a consistent pointer to an object, regardless of the type of pointer used to reach the object.

obj is the pointer whose most derived type you want to determine. src holds type information about the obj object. The return value points to the most derived class that can be made out of obj. If obj is already the object's most derived type, then the return value is obj.

Use typeid to generate the src parameter.


SendObituary function

See also	Global Utility Functions

Header file

ocf/autodefs.h

Syntax

void SendObituary(const void far* obj, const typeinfo& typeinfo);

Description

Notifies OLE that an automated object has been destroyed, preventing any further OLE communication to that object. Use SendObituary in the destructors of objects that are not derived from TAutoBase. (TAutoBase calls SendObituary automatically.)

obj is a pointer to the automated object that is gone.

typeinfo holds type information about the object. Use typeid to generate to generate the typeinfo parameter.


TAutoBase class

See also	Automation Classes

Header File

ocf/autodefs.h

Description

TAutoBase is a base class for deriving automatable objects. The class does only one thing: whenever an object of TAutoBase is destroyed, the destructor notifies OLE that the object is no longer available.

Automated objects are not required to derive from TAutoBase. Doing so is simply a safeguard and matters only if the logic of the program makes it possible for the automated object to be destroyed by non-automated means while still connected to an OLE controller.

If you are using TAutoBase to derive classes with explicit class specifiers that do not match the default specifiers for the application's model, then be sure to define the _AUTOCLASS macro.

Public Destructor

~TAutoBase();


TAutoBase::~TAutoBase

TAutoBase

Syntax

virtual ~TAutoBase();

Description

The virtual destructor—the only member of class TAutoBase—sends OLE an obituary when the object is destroyed. The notification matters in cases where the object might be destroyed by non-automated means, without the knowledge of OLE, while still connected to an automation controller. Sending the obituary prevents a crash if OLE subsequently sends a command to the nonexistent object.


TAutoDetach class

See also	Automation Classes

Header File

ocf/autodefs.h

Description

The TAutoDetach class allows an automated object to notify OLE when it has been destroyed, preventing any further OLE communication to that object. You can add TAutoDetach to a class and the call its Notify method instead of using the SendObituary function or deriving the class from TAutoBase. (TAutoBase calls SendObituary automatically.)

Protected member function

Notify


TAutoDetach::Notify

See also

Syntax

void Notify(int offset, const typeinfo& typeInfo);

Description

Notifies OLE that an object has been destroyed, preventing any further OLE communication to that object.

offset is the offset of the TAutoDetach object inside the object that is destroyed. For example, in the following object, the offset of the TAutoDetach object is 25:

class TObject {

char name[25];

TAutoDetach Detach;

}

typeinfo holds type information about the object. Use typeid to generate to generate the typeinfo parameter.


TLocaleId typedef

See also	General OLE Classes, Macros, and Type Definitions

Header file

ocf/autodefs.h

Syntax

typedef unsigned long TLocaleId;

Description

A locale ID is a 32-bit value that identifies a language. The low half of the value is a 16-bit language ID. In the current OLE definition, the upper word is reserved, so in effect a locale ID is a 32-bit language ID.

Windows uses locale IDs to set the system's default language. ObjectComponents uses locale IDs in automation. An automation controller passes a locale ID to the server with every command. The server is expected to interpret the commands it receives as strings in the given language.

There are two predefined system locale settings in the olenls.h header.

Constant	Meaning

LOCALE_SYSTEM_DEFAULT	The default locale set for the system.

LOCALE_USER_DEFAULT	The default locale set for a particular user (which can differ from the system setting on multiuser systems)


ObjectPtr typedef

Automation Enumerated Types and Type Definitions

Header file

ocf/autodefs.h

Syntax

typedef void* ObjectPtr;

Description

ObjectPtr is a void* that points to a C++ object.


TXAuto class

See also	ObjectComponents Exception Classes

Header File

ocf/autodefs.h

Base Class

TXBase

Description

TXAuto is the exception object that ObjectComponents throws when it encounters an unexpected error while processing automation calls. The possible errors are indicated by the TError nested enum values.

Public Constructor

TXAuto

Public Data Member

ErrorCode

Type Definition

TError


TXAuto::TXAuto

See also	TXAuto

Syntax

TXAuto(TXAuto::TError err);

Description

Constructs an exception object to describe the problem indicated by err.


TXAuto::TError enum

See also	TXAuto

Syntax

enum TError

Description

The values of the enumeration identify possible errors that can occur during automation.

Constant	Meaning

xNoError	No error occurred.

xConversionFailure	Problem converting a value from a VARIANT union to the expected data type.

xNotIDispatch	Attempted to send an automation command to an object that does not execute commands.

xForeignIDispatch	Attempted to send an automation command to an automated object that does not derive from TAutoProxy.

xTypeMismatch	A supplied argument cannot be converted to the required type.

xNoArgSymbol	A command attempted to use more arguments than the server recognizes.

xParameterMissing	An automation call failed to provide a required argument when setting a property value.

xNoDefaultValue	A parameter is missing and no default value was supplied.

xValidateFailure	The code in a user-defined validation hook indicated that the argument values it received are unacceptable.

xExecutionFailure	Execution failed.

xErrorStatus	OLE returned an error code, which is stored in TXAuto::ErrorCode.


TXAuto::ErrorCode

See also	TXAuto

Syntax

TError ErrorCode;

Description

Holds the code that identifies the problem this object was constructed to describe.


TAutoType struct

See also

Header File

ocf/autodefs.h

Description

The TAutoType structure is a static data member of all the automation data type classes, such as TAutoBool and TAutoString. TAutoType makes all these data types self-describing. This is an essential quality for dealing with the VARIANT unions that OLE uses to pass values during automation. Because all the automation types derive from TAutoType, ObjectComponents can process values of any type with the same code. Because TAutoType is self-describing, ObjectComponents can always determine the actual type of any particular item.

Usually you do not have to work with TAutoType directly, just with the automation types that derive from it.

Public Member Function

GetType


TAutoType::GetType

See also	TAutoType

Syntax

uint16 GetType() const;

Description

Returns an integer that identifies a particular data type. The identifiers are defined in the AutoDataType enum.


TAutoEnumerator<> class

See also	Automation Classes

Header File

ocf/autodefs.h

Description

An automation controller creates a TAutoEnumerator object to enumerate items in a collection held by an automation server. A collection can contain any set of similar values or objects that the server chooses to expose as a group. The items in the collection might be numbers in an array, for example, or each one might be an automated object.

The type you pass to the template is the type of value the collection holds. If the collection is a set of integer values, pass int. If the collection holds automated objects, pass the controller's proxy class (derived from TAutoProxy).

At first, a newly created enumerator is empty. After you call Step, the enumerator holds the first value in the collection. To see the value, call Value if the collection contains values of intrinsic data types, such as int or float, or call Object if the collection contains automated objects. Step, Value, and Object are the most important methods of TAutoEnumerator. The others are generally called for you at the right time.

Public Constructors and Destructor

TAutoEnumerator

~TAutoEnumerator

Public Member Functions

Bind

Clear

Object

Step

Unbind

Value


TAutoEnumerator<>::TAutoEnumerator
TAutoEnumerator::TAutoEnumerator

See also	TAutoEnumerator

Syntax 1

TAutoEnumerator();

Description

Constructs an enumerator object but does not attach it to any automated collection.

Syntax 2

TAutoEnumerator(const TAutoEnumerator& copy);

Description

Constructs a new enumerator object by copying an existing one. Both enumerators are attached to the same collection of objects.

Destructor

~TAutoEnumerator();

Description

Detaches the enumerator from its collection before allowing the enumerator to be destroyed.

Remarks

However it is constructed, a newly created TAutoEnumerator object does not yet hold any value. Always call Step to get the first item before calling Value or Object to see the item.


TAutoEnumerator<>::Bind
TAutoEnumerator::Bind

See also	TAutoEnumerator

Syntax

void Bind(TAutoVal& val);

Description

Connects the enumerator to the collection object, val. Bind is called internally when the controller passes the enumerator object to a method that returns a collection.


TAutoEnumerator<>::Clear
TAutoEnumerator::Clear

See also	TAutoEnumerator

Syntax

void Clear();

Description

Empties the enumerator so that it no longer points to any item in the collection. This method is called internally during Step.


TAutoEnumerator<>::Object
TAutoEnumerator::Object

See also	TAutoEnumerator

Syntax

void Object(TAutoProxy& prx);

Description

Returns in prx the current object from the collection. Use Object if the items in the collection are automated objects. If the collection contains data values, then call Value instead.

To advance the enumerator so that Object returns the next object, call Step.


TAutoEnumerator<>::Step
TAutoEnumerator::Step

See also	TAutoEnumerator

Syntax

bool Step();

Description

Advances the enumerator object one step so that Value returns the next item in the collection. Step returns false when called after the enumerator has reached the last item in the collection.


TAutoEnumerator<>::Unbind
TAutoEnumerator::Unbind

See also	TAutoEnumerator

Syntax

void Unbind();

Description

Disconnects the enumerator object from the collection it currently enumerates.


TAutoEnumerator<>::Value
TAutoEnumerator::Value

See also	TAutoEnumerator

Syntax

void Value(T& v);

Description

Returns in v the current item from the collection. Use Value if the items in the collection are data values. If the collection contains objects, then call Object instead.

To advance the enumerator so that Value returns the next item, call Step.


TAutoIterator class

See also	Automation Classes

Header File

ocf/autodefs.h

Description

TAutoIterator is a pure virtual base class for iterator objects. An iterator is used to enumerate a collection of other objects. The iterator's methods let the caller step through a list of objects and examine each one in turn.

An automation server needs to create an iterator in any automated object that represents a collection of other objects. To create an iterator, the server usually inserts an AUTOITERATOR macro in the automation definition of the collection class (after DEFINE_AUTOCLASS).

In most cases, you do not need to work with the iterator class directly because the AUTOITERATOR macro implements the object for you. In cases where the iterator requires a more complex implementation, however, you might need to define the class directly yourself.

You can still declare the class using AUTOITERATOR_DECLARE instead of AUTOITERATOR. This is just a shortcut for writing out all the standard members of an iterator object by hand.

TAutoIterator has five pure virtual members that any derived class must implement. These five functions compose a standard interface for iterators in automated collection objects. They are Init, Test, Step, Return, and Copy. The first four correspond to steps in a for loop that steps through the collection. (See AUTOITERATOR for a description of the correspondence.) Copy creates a duplicate iterator.

The constructors are protected because TAutoIterator should be constructed only by a derived class.

Besides implementing the inherited virtual functions, a class derived from TAutoIterator also typically declares one or more data members that record the iterator's current state. Usually the state variable remembers a position in the sequence of enumerated objects.

TAutoIterator is a COM object and implements the IUnknown interface.

Public Member Functions

Copy

GetSymbol

Init

IUnknown

Return

SetSymbol

Step

Test

Public Destructor

~TAutoIterator

Protected Constructor

TAutoIterator


TAutoIterator::TAutoIterator

TAutoIterator

TAutoIterator (TAutoIterator& copy);

Description

 Constructs an iterator by creating a copy of another iterator. Both iterators enumerate the same collection of objects.

The constructor is protected because only a derived class should construct a TAutoIterator.


TAutoIterator::Copy

See also	TAutoIterator

Syntax

virtual TAutoIterator* Copy() = 0;

Description

Returns a copy of the iterator object. Your implementation should copy the iterator's state variables.


TAutoIterator::GetSymbol

See also	TAutoIterator

Syntax

TAutoSymbol* GetSymbol();

Description

Retrieves the automation symbol associated with the iterator. Usually you do not need to call this function.


TAutoIterator::Init

See also	TAutoIterator

Syntax

virtual void Init() = 0;

Description

Initializes any state variables in the iterator. The primary task of an iterator is to loop through a list of objects enumerating them one by one. Init tells the iterator to prepare for beginning a new pass through the loop. For example, if the iterator's state variable is called index, Init might say

index = 0;


TAutoIterator::operator IUnknown*
TAutoIterator::operator IUnknown

See also	TAutoIterator

Syntax

operator IUnknown*();

Description

Returns a pointer to the iterator's IUnknown OLE interface and calls AddRef on the interface pointer. This operator is called internally to return the iterator to OLE. Usually you do not need to call it directly yourself.


TAutoIterator::Return

See also	TAutoIterator

Syntax

virtual void Return(TAutoVal& value) = 0;

Description

Extracts one item from a collection and returns a reference to it in the value parameter. The primary task of an iterator is to loop through a list of objects enumerating them one by one. Return is the command that retrieves a different item from the collection on each pass through the loop. For example, Return might look like this:

value = (Collection->Array)[Index]

where value is the function's parameter, Collection points to the enclosing collection object, Array is a member of Collection, and Index is the iterator's state variable.

value is type TAutoVal and represents a VARIANT union, which is the format in which OLE passes values. TAutoVal defines conversion operators to handle standard C++ data types as well as C++ strings, TAutoCurrency, TAutoData, and automated C++ objects. The items in a collection can be any of these types.


TAutoIterator::SetSymbol

See also	TAutoIterator

Syntax

void SetSymbol(TAutoSymbol* sym);

Description

Associates an automation symbol with the iterator. SetSymbol is called internally during the construction of the iterator. Usually you do not need to call it directly yourself.


TAutoIterator::Step

See also	TAutoIterator

Syntax

virtual void Step()=0;

Description

Advances the iterator to point to the next item in a collection. The primary task of an iterator is to loop through a list of objects enumerating them one by one. Step is like the i++ statement in a for loop. It changes the state of the iterator to focus on the next item. For example, if the iterator's state variable is called index, Step might simply say:

index++;


TAutoIterator::Test

See also	TAutoIterator

Syntax

virtual bool Test()=0;

Description

Tests whether all items have been enumerated. The primary task of an iterator is to loop through a list of objects, enumerating them one by one. Test returns true if more objects remain to be enumerated and false when it reaches the end of the list. For example, if the iterator's state variable is called index, Test might say

return (index >= NUM_ITEMS);


TAutoIterator::Owner

TAutoIterator

Syntax

TServedObject& Owner;

Description

Holds a reference to the collection object that encloses the iterator. Owner is initialized by the constructor. The undocumented TServedObject class implements the interfaces that a client expects to find on an OLE object. ObjectComponents uses this class internally. Owner can be any automated object.


TAutoObjectByVal<> class

See also	Automation Classes

Header File

ocf/autodefs.h

Base Class

TAutoObjectDelete

Description

An automation server uses this class when an automated method needs to return a copy of an object. Usually you do not have use the class directly because the automation macros make the proper declarations for you.

To return an object, TAutoObjectByVal clones the object by calling its copy constructor. The clone is passed to the automation controller as the return value from some automation command. TAutoObjectByVal holds on to the cloned object until the controller releases it. Then it destroys the object by calling its destructor.

In other respects, TAutoObjectByVal closely resembles its parent class, TAutoObjectDelete.

Public Data Member

operator =

Public Constructors

TAutoObjectByVal


TAutoObjectByVal<>::TAutoObjectByVal

TAutoObjectByVal

Syntax 1

TAutoObjectByVal();

Description

Creates an empty TAutoObjectByVal.

Syntax 2

TAutoObjectByVal(T o);

Description

Creates a TAutoObjectByVal that holds a copy of the object obj. T is the data type passed into the template.


TAutoObjectByVal<>::operator =

TAutoObjectByVal

Syntax

void operator =(T o);

Description

This operator creates a new object of type T by copying the original object, o. The copy is passed to an automation controller as the return value from an automated method. T is the data type passed into the template.


TAutoObjectDelete<> class

See also	Automation Classes

Header File

ocf/autodefs.h

Base Class

TAutoObject

Description

An automation server uses this class when an automated method needs to return an object to an automation controller. Usually you do not have use the class directly because the automation macros make the proper declarations for you.

Like its parent class TAutoObject, TAutoObjectDelete exists in order to hold a pointer to an object and convert it as necessary when the object is passed from server to client through automation calls. The difference between the two classes is that when the automation controller is through with the automated object, TAutoObjectDelete informs the connector object that it can let the automated C++ object call its destructor.

Public Constructors

TAutoObjectDelete

Public Member Functions

operator =

operator =

operator TObjectDescriptor


TAutoObjectDelete<>::TAutoObjectDelete

See also	TAutoObjectDelete

Syntax 1

TAutoObjectDelete();

Description

Creates an empty TAutoObjectDelete object.

Syntax 2

TAutoObjectDelete(T* p);

Description

Creates a TAutoObjectDelete object from a pointer to another object.

Syntax 3

TAutoObjectDelete(T& r);

Description

Creates a TAutoObjectDelete object from a reference to another object.

Remarks

The TAutoObjectDelete constructors do nothing but pass their parameters back to the parent class, TAutoObject.


TAutoObjectDelete<>::operator =

TAutoObjectDelete

Syntax 1

void operator =(T& r);

Description

Tells TAutoObjectDelete to hold a pointer to the object referred to by r.

Syntax 2

void operator =(T* p);

Description

Tells TAutoObjectDelete to hold the pointer p.


TAutoObjectDelete<>::operator TObjectDescriptor

TAutoObjectDelete

Syntax

operator TObjectDescriptor();

Description

Returns type information describing the object.


TAutoBool struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

Use TAutoBool in an automation definition to describe the parameters and return values of automated methods.

Public Data Member

ClassInfo


TAutoBool::ClassInfo

TAutoBool

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoBool holds information that identifies the Boolean data type.


TAutoBoolRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

Use TAutoBoolRef  to return Boolean values of automated methods by reference, not by value.

Public Data Member

ClassInfo


TAutoBoolRef::ClassInfo

TAutoBool

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoBoolRef holds information that identifies the Boolean data type.


TAutoByte struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoByte is an automation data type that helps ObjectComponents provide type information for members of an automated class exposed to OLE. Use TAutoByte in an automation definition to identify a one-byte value.

Public Data Member

ClassInfo


TAutoByte::ClassInfo

TAutoBool

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoByte holds information that identifies a one-byte data item.


TAutoByteRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoByte is an automation data type that helps ObjectComponents provide type information for members of an automated class exposed to OLE. Use TAutoByte in an automation definition to identify a one-byte data item by reference, not by value.

Public Data Member

static TAutoType ClassInfo;


TAutoByteRef::ClassInfo

TAutoByteRef

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoByteRef holds information that identifies a one-byte data item.


TAutoCommand class

Automation Classes

Header File

ocf/autodefs.h

Description

TAutoCommand is an abstract base class for automation command objects. An automation server constructs a command object whenever it receives a command from an automation controller. The command object receives all parameters as VARIANT unions from OLE. The compiler generates calls to command object conversion functions in order to extract the proper C++ data type from the union.

All this happens internally. Normally you should not have to construct or manipulate TAutoCommand objects directly.

Public Constructor and Destructor

TAutoCommand

~TAutoCommand

Type Definitions

typedef bool (*TCommandHook)(TAutoCommand& cmdObj);

typedef const char* (*TErrorMsgHook)(long errCode);

Public Member Functions

ClearFlag

Execute

Fail

GetSymbol

Invoke

IsPropSet

LookupError

Record

Report

Return

SetFlag

SetSymbol

SetErrorMsgHook

SetCommandHook

TestFlag

Undo

Validate

Protected Data Members

Attr

Symbol


TAutoCommand::TAutoCommand 2
TAutoCommand::TAutoCommand

TAutoCommand

Constructor

TAutoCommand(int attr);

Description

Creates a command having the attributes set in the attr flag mask. The flags are defined in the AutoSymFlag enum.

Destructor

virtual ~TAutoCommand();

Description

Destroys the TAutoCommand object.


TAutoCommand::ClearFlag

See also	TAutoCommand

Syntax

void ClearFlag(int mask);

Description

Clears all the flags in mask. The flags are defined in the AutoSymFlag enum.


TAutoCommand::Execute

TAutoCommand

Syntax

virtual void Execute();

Description

Executes the automation command by invoking the internal C++ member of the automated class to which the command belongs.


TAutoCommand::Fail

See also	TAutoCommand

Syntax

void Fail(TXAuto::TError);

Description

Throws whatever exception is indicated by the parameter.


TAutoCommand::GetSymbol

TAutoCommand

Syntax

TAutoSymbol* GetSymbol();

Description

Retrieves the symbol that generates this command.


TAutoCommand::Invoke

See also	TAutoCommand

Syntax

virtual TAutoCommand& Invoke();

Description

Initiates the process of executing a command. The user can override the usual process by supplying a hook with the AUTOINVOKE macro.


TAutoCommand::IsPropSet

TAutoCommand

Syntax

bool IsPropSet();

Description

Returns true if the asSet property flag is set. This flag indicates that the command assigns a value to some property of the automated class and does not return a value.


TAutoCommand::LookupError

See also	TAutoCommand

Syntax

static const char* LookupError(long errCode);

Description

Translates an error code from a function into a message string for the user. errCode is a function status value sent by Report. LookupError works by calling a function you have installed with SetErrorMsgHook. You do not have to call LookupError directly. If you have installed an error message hook, LookupError is called for you at the right time.


TAutoCommand::Record

See also	TAutoCommand

Syntax

virtual int Record(TAutoStack& q);

Description

Records the command and its arguments by calling any hook the programmer might have supplied in the automation declaration with the AUTORECORD macro.

Recording is not supported in the current version of ObjectComponents.


TAutoCommand::Report

See also	TAutoCommand

Syntax

virtual long Report();

Description

The AUTOREPORT macro invokes this function to translate the status code a command returns into an error code.


TAutoCommand::Return

TAutoCommand

Syntax

virtual void Return(TAutoVal& v);

Description

Converts whatever value the internal C++ command returned into a VARIANT union. The converted value is passed to OLE. This is what the automation controller receives as its return value.


TAutoCommand::SetErrorMsgHook

See also	TAutoCommand

Syntax

static TErrorMsgHook SetErrorMsgHook(TErrorMsgHook callback);

Description

Installs a user-defined callback function of type TErrorMsgHook to be called if the command returns an error code.


TAutoCommand::SetCommandHook

See also	TAutoCommand

Syntax

static TCommandHook SetCommandHook(TCommandHook callback);

Description

Installs a user-defined callback function of type TCommandHook to be called whenever the command is executed. The command hook is useful for monitoring automation calls.


TAutoCommand::SetFlag

See also	TAutoCommand

Syntax

void SetFlag(int mask);

Description

Sets all the flags in mask. The flags are defined in the TAutoSymFlag enum.


TAutoCommand::SetSymbol

TAutoCommand

Syntax

void SetSymbol(TAutoSymbol* sym);

Description

Assigns a symbol to the command object. The symbol is set internally. It is taken from the tables built by the automation definition and declaration of the automated class.


TAutoCommand::TestFlag

See also	TAutoCommand

Syntax

bool TestFlag(int mask);

Description

Returns true if any of the flags in mask are set for this command. The flags are defined in the TAutoSymFlag enum.


TAutoCommand::Undo

See also	TAutoCommand

Syntax

virtual TAutoCommand* Undo();

Description

Generates a command for the undo stack by calling any hook the programmer might have supplied in the automation declaration with the AUTOUNDO macro.

Undoing commands is not supported in the current version of ObjectComponents.


TAutoCommand::TCommandHook
TAutoCommand::TCommandHook typedef

See also	TAutoCommand

Syntax

typedef bool (*TCommandHook)(TAutoCommand& cmdObj);

Description

Describes the prototype for a user-defined callback function called during Invoke, before executing the automation command object. cmdObj is the object about to be executed. If the callback returns false, Invoke does not execute the command.


TAutoCommand::TErrorMsgHook typedef

See also	TAutoCommand

Syntax

typedef const char* (*TErrorMsgHook)(long errCode);

Description

Describes the prototype for a user-defined callback function called after Invoke to process any error code the command might return. errCode is the status result. The callback is expected to return a string describing the error for the user.


TAutoCommand::Validate

See also	TAutoCommand

Syntax

virtual bool Validate();

Description

Tests the validity of the command's parameters by executing whatever validation function or expression the programmer supplied in the automation declaration with the AUTOVALIDATE macro.


TAutoCommand::Attr

See also	TAutoCommand

Syntax

int Attr;

Description

Attribute and state flags. The flags are defined in the AutoSymFlag enum.


TAutoCommand::Symbol

TAutoCommand

Syntax

TAutoSymbol* Symbol;

Description

The symbol entry that generates this command. OLE passes this symbol to make this command execute.


TAutoCurrency struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoCurrency is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoCurrency in an automation definition to identify currency values.

Public Data Member

static TAutoType ClassInfo;


TAutoCurrency::ClassInfo

TAutoCurrency

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoCurrency holds information that identifies data as a currency value.


TAutoCurrencyRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoCurrencyRef is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoCurrencyRef in an automation definition to identify currency values passed by pointer, not by value.

Public Data Member

static TAutoType ClassInfo;


TAutoCurrencyRef::ClassInfo

TAutoCurrencyRef

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoCurrencyRef holds information that identifies the TAutoCurrency* data type.


TAutoDate struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoDate is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoDate in an automation definition to identify date values stored as type double.

Public Data Members

ClassInfo

Date

Public Constructor

TAutoDate

Public Member Function

operator double


TAutoDate::TAutoDate

TAutoDate

Syntax 1

TAutoDate();

Description

Creates an empty TAutoDate.

Syntax 2

TAutoDate(double d);

Description

Creates a TAutoDate that initially holds the value in d, assumed to be a date.


TAutoDate::ClassInfo

TAutoDate

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoDate holds information that identifies the date data type.


TAutoDate::Date

TAutoDate

Syntax

double Date;

Description

Stores a date as a 32-bit value.


TAutoDate::operator double

TAutoDate

Syntax

operator double();

Description

Returns the value stored in the Date field of TAutoDate.


TAutoDateRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoDateRef is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoDateRef in an automation definition to identify double date values passed by pointer, not by value.

Public Data Members

static TAutoType ClassInfo;


TAutoDateRef::ClassInfo

TAutoDateRef

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoDateRef holds information that identifies the TAutoDate* data type.


TAutoDispatch struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoDispatch is an automation data type that helps ObjectComponents provide type information for members of an automated class exposed to OLE. Use TAutoDispatch in an automation definition to an IDispatch value.

Public Data Member

ClassInfo


TAutoDispatch::ClassInfo

TAutoDispatch

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoDispatch holds information that identifies the IDispatch data type.


TAutoDouble struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoDouble is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoDouble in an automation definition to identify double values.

Public Data Member

ClassInfo


TAutoDouble::ClassInfo

TAutoDouble

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoDouble holds information that identifies the double data type.


TAutoDoubleRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoDoubleRef is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoDoubleRef in an automation definition to identify double values passed by pointer, not by value.

Public Data Member

ClassInfo


TAutoDoubleRef::ClassInfo

TAutoDoubleRef

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoDoubleRef holds information that identifies the double* data type.


TAutoFloat struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoFloat is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoFloat in an automation definition to identify float values.

Public Data Member

ClassInfo


TAutoFloat::ClassInfo

TAutoFloat

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoFloat holds information that identifies the float data type.


TAutoFloatRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoFloatRef is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoFloatRef in an automation definition to identify float values passed by pointer, not by value.

Public Data Member

ClassInfo


TAutoFloatRef::ClassInfo
TAutoFloat::ClassInfo

TAutoFloatRef

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoFloatRef holds information that identifies the float* data type.


TAutoInt typedef

See also	Automation Data Types

Header File

ocf/autodefs.h

Syntax

#if (MAXINT==MAXSHORT)

typedef TAutoShort TAutoInt;

#else

typedef TAutoLong TAutoInt;

#endif

Description

TAutoInt is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoInt in an automation definition to identify int values. As with int, whether TAutoInt refers to a 16-bit or a 32-bit value depends on the compiler.


TAutoLong struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoLong is an automation data type that helps ObjectComponents provide type information for members of an automated class exposed to OLE. Use TAutoLong in an automation definition to identify long values.

Public Data Member

ClassInfo


TAutoLong::ClassInfo

TAutoLong

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoLong holds information that identifies the long data type.


TAutoLongRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoLongRef is an automation data type that helps ObjectComponents provide type information for members of an automated class exposed to OLE. Use TAutoLongRef in an automation definition to identify a long value passed as a pointer, not by value.

Public Data Member

ClassInfo


TAutoLongRef::ClassInfo

TAutoLong

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoLongRef holds information that identifies the long* data type.


TAutoObject <> class

Automation Classes

Header File

ocf/autodefs.h

Description

TAutoObject holds a pointer to a C++ object. TAutoObject casts the pointer to different data types appropriately when an automation operation requires conversion. It also retrieves type information about the object when needed during automation. Think of TAutoObject as a smart pointer.

ObjectComponents often creates smart pointers for you. Usually you do not need to manipulate TAutoObject objects directly.

Public Constructor

TAutoObject

Public Member Functions

operator *

operator =

operator =

operator =

operator T&

operator T*

TObjectDescriptor

Protected Data Member

P


TAutoObject<>::operator *

TAutoObject

Syntax

T& operator*();

Description

The dereference operator returns a reference to the object whose pointer TAutoObject holds.


TAutoObject<>::operator =

See also	TAutoObject

Syntax 1

void operator=(T* p);

Description

Places the point pointer in the TAutoObject.

Syntax 2

void operator=(T& r);

Description

Places a pointer to the object ref in the TAutoObject.

Syntax 3

void operator=(IDispatch* dp);

Description

Attempts to read type information from the object that owns the IDispatch interface. If it succeeds, the operator places in the TAutoObject a pointer to the C++ object. If it fails, the constructor throws a TXAuto::xTypeMismatch exception.

Remarks

The assignment operators place a pointer to a C++ object in the TAutoObject. They are usually used to initialize the TAutoObject after creating it with the default constructor.


TAutoObject<>::operator T&

TAutoObject

Syntax

operator T&();

Description

Returns a reference to the object whose pointer TAutoObject holds.


TAutoObject::P
TAutoObject<>::P

TAutoObject

Syntax

T* P;

Description

Returns the pointer that TAutoObject holds.


TAutoObject<>::TAutoObject

See also	TAutoObject

Syntax 1

TAutoObject();

Description

Constructs an empty TAutoObject that contains no pointer.

Syntax 2

TAutoObject(T* p);

Description

Constructs a TAutoObject that holds the pointer point.

Syntax 3

TAutoObject(T& r);

Description

Constructs a TAutoObject that holds a pointer to the object ref.

Syntax 4

TAutoObject(IDispatch* dr);

Description

Attempts to read type information from the object that owns the IDispatch interface. If it succeeds, the constructor builds a TAutoObject around a pointer to the C++ object. If it fails, the constructor throws a TXAuto::xTypeMismatch exception.


TAutoObject<>::operator TObjectDescriptor

TAutoObject

Syntax

operator TObjectDescriptor();

Description

Constructs and returns a new object descriptor object based on the pointer that TAutoObject holds. This operator is called internally to obtain type information for constructing an automation object.


TAutoObject::operator T*
TAutoObject<>::operator T*

TAutoObject

Syntax

operator T*();

Description

Returns a pointer to the object TAutoObject holds.


TAutoProxy class

See also	Automation Classes

Header File

ocf/autodefs.h

Description

An automation controller derives classes from TAutoProxy to represent automated OLE objects that it wants to command. To send commands to an automated object, the controller invokes methods on the proxy that represents the object. ObjectComponents connects the proxy to the original so that invoking members of the proxy also invokes members of the automated object.

A proxy object must inherit from TAutoProxy. In the derived class, the controller declares one method for each command it wants to send. The declared methods must match the prototypes of the desired commands. To implement these proxy methods, the controller uses three macros: AUTONAMES, AUTOARGS, and AUTOCALL. The macros insert code that calls down to the base class. TAutoProxy passes the commands to OLE.

Usually you do not have to call anything in TAutoProxy directly. All you have to do is derive your proxy class from TAutoProxy and implement the methods with the proxy macros.

To generate proxy classes quickly and easily, use the AUTOGEN.EXE tool in the OCTOOLS directory. AUTOGEN reads the automation server's type library and writes all the necessary headers and source files for your proxy objects.

Public Destructor

~TAutoProxy

Public Member Functions

Bind

IDispatch&

IDispatch*

IsBound

Lookup

Lookup

Lookup

MustBeBound

SetLang

Unbind

Protected Constructor

TAutoProxy

Protected Member Function

Invoke

Protected Data Members

That

Lang


TAutoProxy::That

Syntax

IDispatch* That;

Description

The IDispatch object.


TAutoProxy::Lang

Syntax

TLangId Lang;

Description

The language identifier.


TAutoProxy::~TAutoProxy

TAutoProxy

Destructor

~TAutoProxy();

Description

Destroys the TAutoProxy object.

The constructors are protected because only derived proxy classes should call them.


TAutoProxy::TAutoProxy

See also	TAutoProxy

Syntax

TAutoProxy(TLangId lang);

Description

Constructs a TAutoProxy object and sets the object to use the language identified by the lang locale ID.


TAutoProxy::Bind

TAutoProxy

Syntax 1

void Bind(IUnknown* obj);

Description

Binds the proxy object to a server identified by a pointer to its IUnknown interface. Throws a TXOle exception for failure.

Syntax 2

void Bind(IUnknown& obj);

Description

Binds the proxy object to a server identified by a reference to its IUnknown interface. Throws a TXOle exception for failure.

Syntax 3

void Bind(const GUID& guid);

Description

Binds the proxy object to a server identified by its globally unique ID (GUID). This is the clsid that the server registered for objects of the type you want to control. Throws a TXOle exception for failure.

Syntax 4

void Bind(char far* progid);

Description

Binds the proxy object to a server identified by its progid. (This is the GUID that the server registered to identify the application itself.) Throws a TXOle exception for failure.

Syntax 5

void Bind(TAutoVal& val);

Description

Attempts to intrepret the value in the TAutoVal union as a reference to an IDispatch object and bind to the IDispatch directly. Throws a TXAuto exception if the object does not support IDispatch.

Syntax 6

void Bind(IDispatch* obj);

Description

Accepts obj as the proxy object's server.

Syntax 7

void Bind(IDispatch& obj);

Accepts obj as the proxy object's server.

Remarks

The Bind function attempts to open a channel of communication to the automation server in order to send commands. More specifically, Bind requests a pointer to the server's IDispatch interface.

Bind is called internally when the object is passed as the return object for another proxy method. Which form of Bind is used depends on what information available to identify the server.


TAutoProxy::operator IDispatch&

TAutoProxy

Syntax

operator IDispatch&();

Description

Returns a reference to the IDispatch interface of the proxy object's server.


TAutoProxy::operator IDispatch*

See also	TAutoProxy

Syntax

operator IDispatch*();

Description

Returns a pointer to the IDispatch interface of the proxy object's server and calls AddRef on the interface pointer.


TAutoProxy::IsBound

TAutoProxy

Syntax

bool IsBound();

Description

Returns true if the server already has a pointer to the IDispatch interface of its server and false if it does not.


TAutoProxy::Lookup

TAutoProxy

Syntax 1

long Lookup(char far* name);

Description

Calls the server to get the ID that matches the name.

Syntax 2

long Lookup(const long id);

Description

Returns the value passed in as id.

Syntax 3

void Lookup(const char* names, long* ids, unsigned count);

Description

Looks up a series of names and returns all their IDs at once. names and ids point to two parallel arrays. count gives the number of elements in both arrays. With a single call to OLE, Lookup fills the ids array with numbers to identify all the names.

Remarks

Given the name of a command or an argument, Lookup calls the server to ask for the corresponding ID values. Although commands and arguments have names for the convenience of programmers, OLE actually identifies them by numbers. A server must find out the ID number in order to execute the command.


TAutoProxy::MustBeBound

TAutoProxy

Syntax

void MustBeBound();

Description

Throws a TXAuto exception if the TAutoProxy object does not have an IDispatch interface for its server. TAutoProxy calls this method internally before performing actions that assume the object is already bound to the server.


TAutoProxy::SetLang

See also	TAutoProxy

Syntax

void SetLang(TLangId lang);

Description

Sets the locale ID that the controller will pass to the server with each command. The locale ID tells the server what language the controller is using.


TAutoProxy::Unbind

See also	TAutoProxy

Syntax

void Unbind();

Description

Decrements the reference count of the proxy object's server and erases internal references to the server.


TAutoProxy::Invoke

See also	TAutoProxy

Syntax

TAutoVal& Invoke(int attr, TAutoProxyArgs& args, long* ids, unsigned named=0);

Description

Sends a command to the automation server. Invoke is called by the AUTOCALL macros.

attr describes the type of command being issued and can be a combination of the AutoCallFlag enum values.

The args object contains all the values passed as arguments to the command.

ids points to an array of ID values identifying the command and the arguments. There should be one ID value for each element in the args array.

names tells how many arguments in args are identified by name.


TAutoShort struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoShort is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoShort in an automation definition to identify short values.

Public Data Member

ClassInfo


TAutoShort::ClassInfo

TAutoShort

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoShort holds information that identifies the short data type.


TAutoShortRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoShortRef is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoShortRef in an automation definition to identify short values passed by pointer, not by value.

Public Data Member

ClassInfo


TAutoShortRef::ClassInfo

TAutoShortRef

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoShortRef holds information that identifies the data type short*.


TAutoStack class

See also	Automation Classes

Header File

ocf/autodefs.h

Description

TAutoStack processes the command stack that an automation controller sends to an automation server through OLE. The command stack contains a dispatch ID identifying a particular command and a set of VARIANT unions containing all the arguments needed to execute the command.

ObjectComponents interprets the dispatch ID and extracts the proper C++ value from each union. It builds a command object (TAutoCommand) and calls the command's Execute method. TAutoCommand in turn invokes the methods you have exposed by declaring them and defining them in your automated classes.

The stack also carries a locale ID identifying the language used in the command. ObjectComponents takes the locale into account when interpreting strings it extracts from the stack. If you have provided localization resources, then ObjectComponents translates to the requested language for you.

Usually you do not have to work with TAutoStack directly. ObjectComponents automatically passes a stack in to the proper command object for you. The command objects are created by the automation declaration macros.

Public Constructor and Destructor

TAutoStack

~TAutoStackTAutoStack

Public Member Function

[]

Public Data Members

ArgCount

LangId

ArgSymbolCount

CurrentArg

DispId

ErrorCode

ErrorMsg

LangId

Owner

Symbol

Protected Data Members

Default

NamedCount

NamedIds

Stack

Constant

SetValue


TAutoStack::DispId

TAutoStack

Syntax

DISPID DispId;

Description

The dispatch identifier.


TAutoStack::ErrorCode

TAutoStack

Syntax

long ErrorCode;

Description

The error code.


TAutoStack::ErrorMsg

TAutoStack

Syntax

const char* ErrorMsg;

Description

The error message.


TAutoStack::Default

TAutoStack

Syntax

TAutoVal Default;

Description

The default stack.


TAutoStack::NamedCount

TAutoStack

Syntax

int NamedCount;

Description

The number of named identifiers.


TAutoStack::NamedIds

TAutoStack

Syntax

long far* NamedIds;

Description

The named identifiers.


TAutoStack::Stack

TAutoStack

Syntax

TAutoVal far* Stack;

Description

The stack.


TAutoStack::TAutoStack

See also	TAutoStack

Constructor

TAutoStack(DISPID dispid, VARIANT far* stack, TLocaleId locale,int argcount, int namedcount, long far* map, TServedObject& owner);

Destructor

~TAutoStack();

Description

The constructor is called only internally. You should not need to construct your own stack.

dispid is the dispatch identifier for the stack.

owner is the automated object to which the command is directed.

stack points to a series of contiguous unions of type VARIANT. The unions contain values or object references passed in automation commands.

locale is a locale ID describing the language the controller is using.

argcount tells how many arguments follow the dispatch ID in the stack.

namedcount tells how many of the arguments were passed with their names. A controller can pass arguments in any order, and even omit optional arguments, if it identifies the arguments it does pass explicitly by the name the server gives them.

if namedcount is greater than zero, then map points to an array of ID values corresponding to the argument names passed by the constructor.

map is a table for translating named argument IDs to argument positions.

Destructor

Destroys the TAutoStack object.


TAutoStack::operator []

See also	TAutoStack

Syntax

TAutoVal& operator[](int index);

Description

Extracts individual arguments from the command stack for use as C++ function arguments. index is a zero-based index into the command's argument list, which follows the order established in the corresponding EXPOSE macro of the automation definition. This operator is called by the command objects generated in the automation declaration.

If index is out of range, the operator throws a TXAuto::xNoArgSymbol exception.


TAutoStack::ArgCount

TAutoStack

Syntax

const int ArgCount;

Description

Holds the number of arguments passed on the command stack (named or unnamed).


TAutoStack::LangId

See also	TAutoStack

Syntax

TLangId LangId;

Description

Holds a number that identifies the language the controller is using to send commands.


TAutoStack::ArgSymbolCount

TAutoStack

Syntax

int ArgSymbolCount;

Description

Holds the number of command arguments exposed to automation.


TAutoStack::CurrentArg

TAutoStack

Syntax

int CurrentArg;

Description

As ObjectComponents processes the arguments on the stack one by one, this member indexes the current argument. When CurrentArg reaches ArgCount, all the arguments have been processed.


TAutoStack::Owner

TAutoStack

Syntax

TServedObject& Owner;

Description

Refers to the automated object that is processing the command on the stack.


TAutoStack::Symbol

See also	TAutoStack

Syntax

TAutoSymbol* Symbol;

Description

Points to the command symbol defined by the corresponding EXPOSE macro in the automation definition.


TAutoStack::SetValue constant

TAutoStack

Syntax

TAutoStack::SetValue

Description

SetValue is a predefined standard dispatch ID. The dispatch ID is a number that identifies a particular command that an automated object can execute. The only two standard dispatch IDs used in ObjectComponents are 0 for an object's default action and -3 for a command that sets the value of a property. SetValue is -3.


TAutoString class

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

An automation server uses TAutoString to describe C string types in an automation definition. The member functions of the TAutoString class facilitate copying and assigning string values with minimal memory reallocations when strings are passed back and forth between servers and controllers.

You do not need to use TAutoString with C++ string objects. For more information, see Automation Data Types.

TAutoString works best with const string values. When passed a non-constant string, TAutoString must make an internal copy. When the string is const, TAutoString knows the value will not change and can skip the copying step. The performance improvement is significant.

Public Constructor and Destructor

TAutoString

~TAutoString

Public Member Functions

operator =

Public Data Member

ClassInfo


TAutoString::ClassInfo

TAutoString

Syntax

static TAutoType ClassInfo;

Description

This static structure holds a number that identifies the data type as a string. All the automation data types hold a similar static identifier so that ObjectComponents can query any of them to determine what they are.


TAutoString::operator =

See also	TAutoString

Syntax

TAutoString& operator =(char* s);

TAutoString& operator =(const char far* s);

TAutoString& operator =(wchar_t* s);

TAutoString& operator =(const wchar_t* s);

TAutoString& operator =(const TAutoString& s);

TAutoString& operator =(TAutoVal& val);

Description

You can assign a TAutoString object to any object of the type shown in the Syntax section.


TAutoString::operator const char far*

TAutoString

Syntax

operator const char far*();

Description

Returns the object's string value in the form of a const C-style string.


TAutoString::TAutoString

TAutoString

Syntax 1

TAutoString(const string& s);

Description

Creates a TAutoString and assigns it the string held in a C++ string object.

Syntax 2

TAutoString(const TAutoString& src);

Description

Creates a new TAutoString that holds the same string value as the copy object.

Syntax 3

TAutoString(TAutoVal& val);

Description

Initializes the new object with the value in a TAutoVal union. TAutoVal represents the VARIANT data type OLE uses to pass values between two applications. It is a union of many types. This constructor extracts the value from the union as a string.

Syntax 4

TAutoString(const char far* str);

Description

Initializes the new object with the value in a const C string.

Syntax 5

TAutoString(BSTR s, bool loan);

Description

Initializes the new object with the value in a BASIC-style string, one preceded by its length and not terminated by null. That is the format OLE uses for passing strings. Set loan to true if the TAutoString object owns the BSTR and false if it only references the BSTR.

Syntax 6

TAutoString(const wchar_t* s);

Description

Initializes the new object with the value in a wchar_t string.

Destructor

~TAutoString();

Description

TAutoString maintains a reference count on the string object it contains. The destructor decrements the reference count.


TAutoStringRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoStringRef is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoStringRef in an automation definition to identify string values passed by pointer, not by value.


TAutoUnknown struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoUnknown is an automation data type that helps ObjectComponents provide type information for members of an automated class exposed to OLE. Use TAutoUnknown in an automation definition to identify an IUnknown value.

Public Data Member

static TAutoType ClassInfo;


TAutoUnknown::ClassInfo

TAutoUnknown

Syntax

static TAutoType ClassInfo;

Description

The ClassInfo member of TAutoUnknown  holds information that identifies the IUnknown data type.


TAutoVal class

See also	Automation Classes

Header File

ocf/autodefs.h

Description

TAutoVal duplicates the VARIANT type that OLE uses to pass values between an automation server and controller. It also adds access methods to retrieve the value in the VARIANT. A VARIANT can be cast to type TAutoVal, and TAutoVal can be cast to a VARIANT.

A VARIANT is a large union with fields of many different data types. A large set of overloaded assignment operators allow many different kinds of values to be stored in a TAutoVal object. Each assignment operator also records internally a number that identifies the type of value just received. A similar set of conversion operators allows the value in the object to be cast to different types of values. Whether a particular conversion succeeds depends on the type of value in the object. A string cannot be cast to some other object, for example. If the conversion fails, TAutoVal throws an exception of type TXAuto::xConversionFailure.

ObjectComponents treats the data passed between an automation server and controller as a stack of unions. The stack is TAutoStack, and the items on the stack are TAutoVal. Because the server and controller are built separately and can use different programming languages, data passed between them cannot retain an intrinsic type. Command identifiers and argument values are passed as VARIANTs. The recipient of a VARIANT value must rely on the item's context in order to determine what type the value is supposed to be. For example, when it sees a dispatch ID for a command that expects two integer arguments, the application extracts integers from the next two VARIANTs.

Public Constructors

TAutoVal::TAutoVal

Public Destructor

TAutoVal::~TAutoVal

Public Member Functions

operator =

operator char

operator char far*

operator signed char

operator signed char far*

operator unsigned char

operator unsigned char far*

operator double

operator double far*

operator float

operator float far*

operator IDispatch&

operator IDispatch*

operator int

operator int far*

operator unsigned int

operator IUnknown&

operator IUnknown*

operator long

operator long far*

operator unsigned long

operator unsigned long far*

operator short

operator short far*

operator unsigned short

operator unsigned short far*

operator string

operator TAutoBool

operator TAutoBoolRef

operator TAutoCurrency

operator TAutoCurrency far*

operator TAutoDate

operator TAutoDate far*

operator TBool

operator TBool far*

operator TUString*

Clear

Copy

DereferenceVariant

GetArray

GetDataType

GetLanguage

GetLocale

GetObjDesc

IsRef

SetByRef

SetLocale

StrVal

Restore


TAutoVal::TAutoVal

TAutoVal

Syntaxes

TAutoVal();

TAutoVal(const TAutoVal&	src);

TAutoVal(unsigned char	i);

TAutoVal(signed char	i);

TAutoVal(char	i);

TAutoVal(unsigned char*	p);

TAutoVal(signed char*	p);

TAutoVal(char*	p);

TAutoVal(int	i);

TAutoVal(int*	p);

TAutoVal(unsigned int	i);

TAutoVal(unsigned int*	p);

TAutoVal(unsigned short	i);

TAutoVal(unsigned short*	p);

TAutoVal(long	i);

TAutoVal(long*	p);

TAutoVal(unsigned long	i);

TAutoVal(unsigned long*	p);

TAutoVal(short	i);

TAutoVal(short*	p);

TAutoVal(float	i);

TAutoVal(float*	p);

TAutoVal(double	i);

TAutoVal(double*	p);

TAutoVal(TBool	i);

TAutoVal(TBool*	p);

TAutoVal(TAutoBool	i);

TAutoVal(TAutoBoolRef	p);

TAutoVal(const string&	s);

TAutoVal(TAutoString	s);

TAutoVal(TAutoCurrency	i);

TAutoVal(TAutoCurrency*	p);

TAutoVal(TAutoDate	i);

TAutoVal(TAutoDate*	i);

TAutoVal(IDispatch*	ifc);

TAutoVal(IUnknown*	ifc);

TAutoVal(VARIANT&	v);

TAutoVal(const TNoArg&	n);

Description

Creates a TAutoVal object from the given object.

Note:	You can use the TAutoVal(TAutoBool i) and TAutoVal(TAutoBoolRef) constructors only if BI_UNIQUE_BOOL is defined.


TAutoVal::~TAutoVal

TAutoVal

Syntax

~TAutoVal();

Description

Calls the Clear function.


TAutoVal::TAutoBool

TAutoVal

Syntax

operator TAutoBool();

Description

Returns the value in the object as a pointer to a TAutoBool.


TAutoVal::TAutoBoolRef

TAutoVal

Syntax

operator TAutoBoolRef();

Description

Returns the value in the object as a pointer to a TAutoBoolRef.


TAutoVal::char

TAutoVal

Syntax

operator char();

Description

Returns the value in the object as a char.


TAutoVal::char far*

TAutoVal

Syntax

operator char far*();

Description

Returns the value in the object as a pointer to a char.


TAutoVal::signed char

TAutoVal

Syntax

operator signed char();

Description

Returns the value in the object as a signed char.


TAutoVal::signed char far*

TAutoVal

Syntax

operator signed char far*();

Description

Returns the value in the object as a pointer to a signed char.


TAutoVal::unsigned char

TAutoVal

Syntax

operator unsigned char();

Description

Returns the value in the object as an unsigned char.


TAutoVal::unsigned char far*

TAutoVal

Syntax

operator unsigned char far*();

Description

Returns the value in the object as a pointer to an unsigned char.


TAutoVal::DereferenceVariant

TAutoVal

Syntax

TAutoVal far* DereferenceVariant();

Description

Returns a pointer to the object.


TAutoVal::GetArray

TAutoVal

Syntax

SAFEARRAY far* GetArray();

Description

Returns the value in the parray data member.


TAutoVal::GetLanguage

TAutoVal

Syntax

TLangId GetLanguage() const;

Description

Returns the language identifier for the object.


TAutoVal::GetLocale

TAutoVal

Syntax

TLocaleId GetLocale() const;

Description

Returns the locale identifier for the object.


TAutoVal::GetObjDesc

TAutoVal

Syntax

bool GetObjDesc(TObjectDescriptor&);

Description

Stores the descriptor for the object in TObjectDescriptor variable.


TAutoVal::unsigned int

TAutoVal

Syntax

operator unsigned int();

Description

Returns the value in the object as a pointer to an unsigned int.


TAutoVal::unsigned long far*

TAutoVal

Syntax

operator unsigned long far*();

Description

Returns the value in the object as a pointer to an unsigned long integer.


TAutoVal::SetByRef

TAutoVal

Syntax

void far* SetByRef(AutoDataType datatype)

Description

Returns a pointer (of the type you specify in the datatype parameter) to the value of the object. For example, if you specify atShort for the datatype parameter, SetByValue returns a short pointer to the value.


TAutoVal::SetLocale

TAutoVal

Syntax

void SetLocale(TLocaleId);

Description

Sets the locale identifier for the object.


TAutoVal::unsigned short

TAutoVal

Syntax

operator unsigned short();

Description

Returns the value in the object as an unsigned short integer.


TAutoVal::unsigned short far*

TAutoVal

Syntax

operator unsigned short far*();

Description

Returns the value in the object as a pointer to an unsigned short integer.


TAutoVal::StrVal

TAutoVal

Syntax

TString StrVal();

Description

Returns the string value of the object.


TAutoVal::Restore

TAutoVal

Syntax

void Restore();

Description

Restores the value in the object.


TAutoVal::operator int

TAutoVal

Syntax

operator int();

Description

Returns the value in the object as an integer.


TAutoVal::operator int far*

TAutoVal

Syntax

operator int far*();

Description

Returns a pointer to an int.


TAutoVal::operator short

TAutoVal

Syntax

operator short();

Description

Returns the value in the object as a short integer.


TAutoVal::operator short far*

TAutoVal

Syntax

operator short far*();

Description

Returns a pointer to a short integer.


TAutoVal::operator long

TAutoVal

Syntax

operator long();

Description

Returns the value in the object as a long integer.


TAutoVal::operator long far*

TAutoVal

Syntax

operator long far*();

Description

Returns a pointer to a long integer.


TAutoVal::operator unsigned long

TAutoVal

Syntax

operator unsigned long();

Description

Returns the value in the object as an unsigned long integer.


TAutoVal::operator unsigned long far*

TAutoVal

Syntax

operator unsigned long far*();

Description

Returns a pointer to a long integer. (TAutoVal does not distinguish long from unsigned long.)


TAutoVal::operator unsigned int

TAutoVal

Syntax

operator unsigned int();

Description

Returns the value in the object as an unsigned integer value.


TAutoVal::operator float

TAutoVal

Syntax

operator float();

Description

Returns the value in the object as a floating-point value.


TAutoVal::operator float far*

TAutoVal

Syntax

operator float far*();

Description

Returns a pointer to a floating-point value.


TAutoVal::operator double

TAutoVal

Syntax

operator double();

Description

Returns the value in the object as a double value.


TAutoVal::operator double far*

TAutoVal

Syntax

operator double far*();

Description

Returns a pointer to a double value.


TAutoVal::operator TBool

TAutoVal

Syntax

operator TBool();

Description

Returns the value in the object as a Boolean value.


TAutoVal::operator TBool far*

TAutoVal

Syntax

operator TBool far*();

Description

Returns a pointer to a Boolean value.


TAutoVal::operator TAutoCurrency

See also	TAutoVal

Syntax

operator TAutoCurrency();

Description

Returns the value in the object as a currency value.


TAutoVal::operator TAutoCurrency far*

See also	TAutoVal

Syntax

operator TAutoCurrency far*();

Description

Returns a pointer to a currency value.


TAutoVal::operator TAutoDate

See also	TAutoVal

Syntax

operator TAutoDate();

Description

Returns the value in the object as a date value.


TAutoVal::operator TAutoDate far*

See also	TAutoVal

Syntax

operator TAutoDate far*();

Description

Returns a pointer to a date value.


TAutoVal::operator string

TAutoVal

Syntax

operator string();

Description

Returns the value in the object as a C++ string object.


TAutoVal::operator TUString*

TAutoVal

Syntax

operator TUString*();

Description

Returns the value in the object as a TUString object. TUString is a reference-counted union of various string representations. It is used internally by ObjectComponents for implementing TAutoString.


TAutoVal::operator IDispatch*

See also	TAutoVal

Syntax

operator IDispatch*();

Description

Extracts an IDispatch interface from the value in the TAutoVal object. IDispatch is the standard OLE interface supported by automatable objects. This function also calls the interface's AddRef method.


TAutoVal::operator IDispatch&

See also	TAutoVal

Syntax

operator IDispatch&();

Description

Extracts an IDispatch interface from the value in the TAutoVal object. IDispatch is the standard OLE interface supported by automatable objects. This method does not call AddRef on the IDispatch interface.


TAutoVal::operator IUnknown*()
TAutoVal::operator IUnknown*

See also	TAutoVal

Syntax

operator IUnknown*();

Description

Extracts an IUnknown interface from the value in the TAutoVal object. IUnknown is the standard OLE interface supported by all objects. This method calls AddRef on the IUnknown interface.


TAutoVal::operator IUnknown&

See also	TAutoVal

Syntax

operator IUnknown&();

Description

Extracts an IUnknown interface from the value in the TAutoVal object. IUnknown is the standard OLE interface supported by all objects. This method does not call AddRef on the IUnknown interface.


TAutoVal::operator =

See also	TAutoVal

Syntax

void operator =(char far* p);

void operator =(char i);

void operator =(signed char far* p);

void operator =(signed char i);

void operator =(unsigned char far* p);

void operator =(unsigned char i);

void operator =(double far* p);

void operator =(double i);

void operator =(float far* p);

void operator =(float i);

void operator =(int far* p);

void operator =(int i);

void operator =(unsigned int far* p);

void operator =(unsigned int i);

void operator =(long far* p);

void operator =(long i);

void operator =(unsigned long far* p);

void operator =(unsigned long i);

void operator =(short far* p);

void operator =(short i);

void operator =(unsigned short far* p);

void operator =(unsigned short i);

void operator =(const string& s);

void operator =(IDispatch* ifc);

void operator =(IUnknown* ifc);

void operator =(TAutoBool i);

void operator =(TAutoBoolRef p);

void operator =(TAutoCurrency i);

void operator =(TAutoCurrency far* p);

void operator =(TAutoDate far* i);

void operator =(TAutoDate i);

void operator =(TAutoString s);

void operator =(TAutoVoid);

void operator =(TBool far* p);

void operator =(TBool i);

void operator =(TObjectDescriptor od);

void operator =(VARIANT& v);

void operator =(const TNoArg& n);

Description

Assignment operators initialize TAutoVal by placing in the object both the assigned value and an ID to show the type of the assigned value.

This table describes those data types that are not standard C types.

Type	Description

IDispatch	A class ObjectComponents uses internally to implement the standard OLE interface called IDispatch, supported by automatable objects

IUnknown	A class that ObjectComponents uses internally to implement the standard IUnknown OLE interface, supported by all OLE objects

string	C++ string object

TAutoCurrency	An automation data type that holds a currency value

TAutoString	An automation data type that holds a C-style string value

TAutoVoid	An automation data type that represents a void return

TObjectDescriptor	A class that ObjectComponents uses internally to hold information about an OLE object

VARIANT	A raw Variant, as defined in the \WIN16\VARIANT.H file.

TNoArg	A struct for creating a TAutoVal object that can be passed instead of an actual value as a method’s optional parameter.


TAutoVal::GetDataType

TAutoVal

Syntax

int GetDataType();

Description

Returns an integer identifying the type of value that was assigned to the union.


TAutoVal::Clear

See also	TAutoVal

Syntax

void Clear();

Description

Clears the value stored in the object, leaving it empty. This method cannot be called on the objects managed by TAutoStack.


TAutoVal::Copy

See also	TAutoVal

Syntax

void Copy(const TAutoVal& copy);

Description

Copies the TAutoVal object into copy. Intelligently allocates space for a string, if needed, and calls AddRef if the value in the union is an OLE object.


TAutoVal::IsRef

TAutoVal

Syntax

bool IsRef();

Description

Returns true if the value assigned to the union is a reference to a value.


TAutoVariantRef struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoVariantRef is an automation data type that helps ObjectComponents provide type checking for members of an automated class exposed to OLE. Use TAutoVariantRef in an automation definition to identify variant values passed by pointer, not by value.


TNoArg struct

Automation Data Types

Header File

ocf/autodefs.h

Syntax

struct TNoArg;

Description

A dummy structure. For a method’s optional parameter that you don’t want to specify, use a TAutoVal object constructed from a TNoArg object. ObjectComponents automatically replaces the object with a VT_ERROR VARIANT (SCODE=DISP_E_PARAMNOTFOUND), simulating Visual Basic’s handling of unspecified parameters.


TAutoVoid struct

See also	Automation Data Types

Header File

ocf/autodefs.h

Description

TAutoVoid is an automation data type like TAutoShort and TAutoBool. Use it in an automation definition to describe functions that return no value.

The purpose of the structure is to implement the assignment of void to a TAutoVal.

Public Data Member

static TAutoType ClassInfo;


TAutoVoid::ClassInfo

See also	TAutoVoid

Syntax

static TAutoType ClassInfo;

Description

As with any automation data type, the ClassInfo member holds a value that identifies a data type, in this case void.


AutoCallFlag enum

See also

Header File

ocf/autodefs.h

Syntax

enum AutoCallFlag

Description

These flags identify types of class members. Automation servers use them in their automation declarations and automation controllers pass them when the invoke commands. Usually you don't have to use these constants directly because they are set for you by the automation declaration macros and the Automation Proxy Macros.

Constant	Meaning

acMethod	Member is a method.

acPropGet	Member gets the value of a property.

acPropSet	Member sets the value of a property.

acVoidRet	Member returns void.

The values are bit flags. Combine them with the bitwise OR operator (|).


_AUTOCLASS macro

Header File

ocf/autodefs.h

Description

_AUTOCLASS is the class modifier that ObjectComponents uses to declare the base classes and member objects it creates inside your classes for automation. As long as your own classes use the application's ambient memory model, you do not have to worry about _AUTOCLASS, which by default is defined as nothing. If, however, you declare your automation classes with a modifier that differs from the ambient class model, then the classes (such as TAutoBase) that ObjectComponents defines must be modified to match. To accomplish the modification, define _AUTOCLASS yourself. For example:

#define _AUTOCLASS __far


AutoDataType enum

See also	Automation Enumerated Types and Type Definitions

Header File

ocf/autodefs.h

Syntax

enum AutoDataType

Description

These flags identify automation data types. The types correspond to standard OLE 2 data types. The TAutoVal class uses the flags to guide its conversions to and from the VARIANT unions that OLE passes between programs.

Constant	Meaning

atVoid	void

atNull	SQL-style null

atShort	2-byte signed int

atLong	4-byte signed int

atFloat	4-byte real

atDouble	8-byte real

atCurrency	currency

atDatetime	datetime as double

atString	BSTR, string preceded by length

atObject	IDispatch*

atError	SCODE

atBool	true = -1, false = 0

atVariant	VARIANT FAR*

atUnknown	IUnknown*

atByte	byte or unsigned char

atTypeMask	Base type code without bit flags.

atOLE2Mask	Type code with bit flags.

The preceding flags are mutually exclusive. A value can belong to only one type. Any of the type flags can, however, be combined with the following bit flags.

Bit Flag	Meaning

atSafeArray	The value is a BASIC-type bounded array.

atByRef	The value is a reference to an object.

atEnum	The value is an enumeration of some type.

atAutoClass	The value is a TAutoClass object


AutoSymFlag enum

See also	Automation Enumerated Types and Type Definitions

Header File

ocf/autodefs.h

Syntax

enum AutoSymFlag

Description

These flags are used in the TAutoCommand class to describe attributes of an automation command. The flags tell whether the command is a method or a property, whether arguments are passed by value or by reference, and whether it should be visible in type information browsers.

Constant	Meaning

asAnyCommand	Any command: method, property access, object builder.

asOleType	Method or property exposed for OLE.

asMethod	Method.

asGet	Returns the value of a property.

asIterator	Iterator property; used to enumerate items in a collection.

asSet	Set property value.

asGetSet	Get or set a property value.

asBuild	Constructor command (not supported by OLE 2.01).

asFactory	For creating objects or determining class.

asClass	Extension to another class symbol table.

asArgument	Property that returns an object.

asNotTerminator	A symbol without a terminator.

asBindable	Sends OnChanged notification.

asRequestEdit	Sends OnRequest edit before change.

asDisplayBind	User-display of bindable.

asDefaultBind	This property only is the default (redundant).

asHidden	Not visible to normal browsing.

asPersistent	Property is persistent.


AUTOSTAT Macros

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Description

Use the AUTOSTAT in an automation declaration (after DEFINE_AUTOCLASS) to make static member functions and global functions accessible to OLE.

All versions of the AUTOSTAT macro have similar parameters. name is an internal name you assign to the function. ObjectComponents uses the name to keep track of all the automated members. The only other place you use this internal name is in the corresponding automation definition.

func is the name of the static or global function.

ret is the type of value the function returns.

type1, t1, t2, t3, and t4 are the types of the function's arguments.

options is a place to insert a hook, code to be called each time the automation command is executed. Hooks can record, undo, or validate commands. See Automation Hook Macros for more details. options can be omitted, but a comma must follow the preceding argument anyway.

The return types and argument types are usually normal C++ data types, but string and object values require special treatment. For more information, see Automation Data Types.

Macro	Meaning

AUTOSTAT0(name, func, ret, options)	The static function func is assigned the symbol name. It takes no arguments and returns a value of type ret.

AUTOSTAT0V(name, func, options)	The static function func takes no arguments and returns no value.

AUTOSTAT1(name, func, ret, type1, options)	func takes one argument of type type1 and returns a value of type ret.

AUTOSTAT1V(name, func, type1, options)	func takes one argument of type type1 and returns no value.

AUTOSTAT2(name, func, ret, t1, t2, options)	func takes two arguments of types t1 and t2 and returns a value of type ret.

AUTOSTAT2V(name, func, t1,t2, options)	func takes two arguments and returns no value.

AUTOSTAT3(name, func, ret, t1,t2, t3, options)	func takes three arguments and returns a value.

AUTOSTAT3V(name, func, t1, t2, t3, options)	func takes three arguments and returns no value.

AUTOSTAT4(name, func, ret, t1, t2, t3, t4, options)	func takes four arguments and returns a value.

AUTOSTAT4V(name, func, t1, t2, t3, t4, options)	func takes four arguments and returns no value.


AUTOTHIS Macro

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Syntax

AUTOTHIS(name, type, options)

Description

An automation server uses the AUTOTHIS macro in its automation declaration (after DEFINE_AUTOCLASS) if it wants to expose the C++ object itself as a member of the automated OLE object.

name is an internal name you assign to the property. ObjectComponents uses the name to keep track of all the automated members. The only other place you use this internal name is in the corresponding automation definition.

type must be TAutoObject<T>, where T is the type of the automated class.

options is a place to insert a hook, code to be called each time a controller asks for this property. Hooks can record, undo, or validate commands. options can be omitted, but a comma must follow the preceding argument anyway. For more details, see Automation Hook Macros.


AUTOUNDO Macro

See also	Automation Hook Macros

Header File

ocf/automacr.h

Syntax

AUTOUNDO(code)

Description

An automation server uses AUTOUNDO in an automation declaration macro to hook in user-defined code that records whatever information the application needs to reverse the command later. Usually it adds information to a user-maintained undo stack. The information might include the parameters that execute the inverse of the original command, for example. To undo a series of actions, the program can pop commands off the undo stack and execute them. code is the expression or function that records information.

Undoing commands is not supported in the current version of ObjectComponents.


AUTOVALIDATE Macro

See also	Automation Hook Macros

Header File

ocf/automacr.h

Syntax

AUTOVALIDATE(condition)

Description

An automation server uses AUTOVALIDATE in an automation declaration macro to hook in user-defined code that confirms the validity of received arguments before passing them on to be processed in a command. condition is an expression or function that evaluates to true if the arguments received are valid for the command and false if not. If the expression returns false, OLE throws an exception in the controller application.


AUTODETACH Macro

See also

Header File

ocf/automacr.h

Syntax

AUTODETACH

Description

An automation server uses this macro in its automation declaration (after DECLARE_AUTOCLASS) to ensure that whenever the automated object is destroyed OLE receives notification. Sending the object's obituary to OLE prevents crashes should a controller attempt to manipulate the nonexistent object. The obituary is necessary only if the logic of your program makes it possible for the automated object to be destroyed by non-automated means while still connected to the controller.

Deriving a class from TAutoBase serves exactly the same purpose. The advantage of AUTODETACH is that you can use it to automate classes you did not create and whose derivation you cannot control.


AUTOENUM Macros

See also

Header File

ocf/automacr.h

Description

An automation server uses the AUTOENUM macros to expose enumerated values to automation controllers. For example, if the server wants the controller to pass actions into a DoThis command, the server might create an enumerated type containing values such as Play, Stop, and Rewind. To make these values available to the controller, the server must create an AUTOENUM table. In this example, the table consists of three AUTOENUM macros, one for each enumerated value.

DEFINE_AUTOENUM(TAction, TAutoShort);

 AUTOENUM("Play", Play)

 AUTOENUM("Stop", Stop)

 AUTOENUM("Rewind", Rewind);

END_AUTOENUM(TAction, TAutoShort)

Macro	Meaning

DEFINE_AUTOENUM(cls, type)	Begins an AUTOENUM table. cls is the name of the automated enumeration type (not the name of the C++ enumerated type). You invent this name. The only other place it appears is in the application's automation definition.

type is the automation data type that describes what kind of values are being enumerated. For more information, see Automation Data Types.

AUTOENUM(name, val)	name is the public string that a controller uses to refer to one in a series of enumerated values. val is the internal value the server associates with name.

END_AUTOENUM(cls, type)	Ends an AUTOENUM table. cls and type are the same as for DEFINE_AUTOENUM.


AUTOFLAG Macro

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Syntax

AUTOFLAG(name, data, mask, options)

Description

An automation server uses AUTOFLAG in an automation declaration (after DECLARE_AUTOCLASS) to expose for automation a single bit from a set of bit flags.

name is an internal name that you assign to the bit. ObjectComponents uses the internal names to keep track of all the automated members. The only other place you use this name is in the subsequent automation definition (after DEFINE_AUTOCLASS.)

data is the C++ name of a data member that holds a set of bit flags.

mask is a value with one bit set marking the position of the exposed flag in data.

options is a place to insert a hook, code to be called each time the automation command is executed. Hooks can record, undo, or validate commands. See Automation Hook Macros for more details. options can be omitted, but a comma must follow the preceding argument anyway.


AUTOFUNC Macros

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Description

An automation server uses AUTOFUNC macros in an automation declaration (after DECLARE_AUTOCLASS) to make member functions of an automated class accessible through OLE.

In every version of the macro the first parameter, name, is an internal name that you assign to the function. ObjectComponents uses the internal names to keep track of all the automated members. The only other place you use this name is in the subsequent automation definition (after DEFINE_AUTOCLASS).

func is the C++ name of the member function, the name you normally use in your source code.

ret is the type of data the function returns. type1, t1, t2, t3, and t4 represent the data types of the parameters. In most cases, all these data types should be normal C++ data types, but if the data member is a string or an object then specify TAutoString or one of the TAutoObject classes instead. For more details, see Automation Data Types. Also, automated functions cannot return const values. Do not use const in a ret type.

options is a place to insert a hook, code to be called each time the automation command is executed. Hooks can record, undo, or validate commands. For more details, see Automation Hook Macros. options can be omitted, but a comma must follow the preceding argument anyway.

The automacr.h header defines versions of this macro that accept up to three arguments. To generate versions that accept more arguments, use the MACROGEN.EXE utility.

Macro	Meaning

AUTOFUNC0(name, func, ret, options)	The function takes no parameters and returns a value of type ret.

AUTOFUNC0V(name, func, options)	The function takes no parameters and returns void.

AUTOFUNC1(name, func, ret, type1, options)	The function takes one parameter of type type1 and returns a value of type ret.

AUTOFUNC1V(name, func, type1, options)	The function takes one parameter of type type1 and returns void.

AUTOFUNC2(name, func, ret, t1, t2, options)	The function takes two parameters of types t1 and t2. It returns a value of type ret.

AUTOFUNC2V(name, func, t1, t2, options)	The function takes two parameters and returns void.

AUTOFUNC3(name, func, ret, t1, t2, t3, options)	The function takes three parameters and returns a value.

AUTOFUNC3V(name, func, t1 ,t2, t3, options)	The function takes three parameters and returns void.

AUTOFUNC4(name, func, ret, t1, t2, t3, t4, options)	The function takes four parameters and returns a value.

AUTOFUNC4V(name, func, t1, t2, t3, t4, options)	The function takes four parameters and returns void.


AUTOINVOKE Macro

See also	Automation Hook Macros

Header File

ocf/automacr.h

Syntax

AUTOINVOKE(code)

Description

An automation server uses AUTOINVOKE in an automation declaration macro to hook in user-defined code for ObjectComponents to execute every time the application receives a particular automation command. code is the expression or function call to execute on each command.

Create an AUTOINVOKE hook if you want to override the normal execution sequence.


AUTOITERATOR Macros

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Description

An iterator is an object used to enumerate a collection of objects. An iterator's methods let the caller step through a list of objects and examine each one in turn.

An automation server needs to create an iterator in any automated object that represents a collection of other objects. To create an iterator, the server adds one of the AUTOITERATOR macros to the class's automation definition (after DEFINE_AUTOCLASS). The iterator must also be exposed in the automation definition with the EXPOSE_ITERATOR macro.

Macro	Meaning

AUTOITERATOR(state, init, test, step, extract)	Implements a collection iterator within the automated class.

AUTOITERATOR_DECLARE(state)	Declares but does not implement a collection iterator within the automated class. Use this if your iterator's implementation is too complex for AUTOITERATOR.

The five arguments of AUTOITERATOR define the iteration algorithm for the collection class. Only one auto-iterator can exist within a class, so there is no need for a special internal name. The five arguments each represent a code fragment, and they follow the sequence of code in a for loop. As the examples show, because the iterator object is nested within the automated collection class, it can refer to members of the class.

Parameter	Example	Meaning

state	int Index	Declaration of state variables. This must be the same declaration previously given in AUTOITERATOR_DECLARE.

init	Index = 0	Statements (usually assignments) executed to initialize the loop.

test	Index < This->Total	Boolean expression tested each time through the loop.

step	Index++	Statements executed each time through the loop.

extract	(This->Array)[Index]	Expression that returns the successive objects in the collection.

Within the parameters, This (note the capital T) points to the enclosing collection object, not to the nested iterator object.

Commas cannot be used except inside parentheses. Semicolons can be used to separate multiple statements, but not to end a macro argument.

If you use AUTOITERATOR_DECLARE instead of AUTOITERATOR, then you must implement the state variables and these methods, corresponding to the steps described for AUTOITERATOR.

void Init();

bool Test();

void Step();

void Return(TAutoVal& v);


AUTONAMES Macros

See also	Automation Proxy Macros

Header File

ocf/automacr.h

Description

The AUTONAMES macros are the first in three sets of macros that an automation controller uses to implement methods in its proxy objects. AUTONAMES macros assign names to any arguments that the controller wants to reference by name. Named parameters have default values and are not required in a command. If a command has fifteen parameters and ten of them have names and default values, then the controller must always pass the five unnamed parameters and can choose to pass any subset of the remaining ten, identifying them by their names.

The second set of macros, AUTOARGS Macros, describe the data types of unnamed arguments that must always be passed in the command. The third set, AUTOCALL, tells whether the command is a method or a property and what it returns.

In the macros that follow, id is a numeric ID for a method, fname is a string naming a method, and n1, n2, n3, and n4 are strings assigned as argument names. Most of the macros need the function name to identify the function, but if a function has no named arguments, then you can pass its identifying number instead.

Macro	Meaning

AUTONAMES0(id)	Function id has no named arguments.

AUTONAMES0(fname)	Function fname has no named arguments.

AUTONAMES1(fname, n1)	Function fname has one named argument, n1.

AUTONAMES2(fname, n1, n2)	Function fname has two named arguments, n1 and n2.

AUTONAMES3(fname, n1, n2, n3)	Function fname has three named arguments, n1, n2, and n3.

The automacr.h header defines macros that accept up to ten arguments (AUTONAMES10). To generate versions that accept more arguments, use the MACROGEN.EXE utility.


AUTONOHOOK Macro

See also	Automation Hook Macros

Header File

ocf/automacr.h

Syntax

AUTONOHOOK

Description

An automation server uses AUTONOHOOK in an automation declaration macro to prevent anyone from hooking the command. Not even ObjectComponents can monitor the call.

AUTONOHOOK is for advanced uses only.


AUTOPROP Macros

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Description

An automation server uses AUTOPROP macros in its automation declaration (after AUTOITERATOR macros to the class's automation definition (after DEFINE_AUTOCLASS) to make properties of an automated class accessible to OLE. A property is data that cannot be read or written directly, only through a set of access functions (for example, GetPosition and SetPosition.)

A server can implement the access functions any way it likes. Because only the access functions are exposed, the property does not have to be a data member. In other words, GetPosition and SetPosition would not have to refer to a data member of type TPoint. They might query the system for the cursor position and return the answer.

The three AUTOPROP macros have similar parameters. name is an internal name you assign to the property. ObjectComponents uses the name to keep track of all the automated members. The only other place you use this internal name is in the corresponding automation definition.

get and set are the access functions. A read-only property has just a get function. A write-only property has just a set function.

type is the property's data type. This is usually a C++ data type, but string and object properties require special treatment. For more information, see Automation Data Types.

options is a place to insert a hook, code to be called each time the automation command is executed. Hooks can record, undo, or validate commands. options can be omitted, but a comma must follow the preceding argument anyway. For more details, see Automation Hook Macros.

Macro	Meaning

AUTOPROP(name, get, set, type, options)	The property can be read and written.

AUTOPROPRO(name, get, type, options)	The property can only be read, not changed.

AUTOPROPWO(name, set, type, options)	The property can be changed but not read (rare).


AUTOPROXY Macro

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Syntax

AUTOPROXY(name, proxyMember, options)

Description

An automation server uses AUTOPROXY in an automation declaration (after the DECLARE_AUTOCLASS macro) when automating a property whose value is an external automated object (one derived from TAutoProxy). AUTOPROXY is useful only in servers that also act as controllers and so create TAutoProxy-derived classes to send automation commands.

name is an internal name you assign to the property. ObjectComponents uses the name to keep track of all the automated members. The only other place you use this internal name is in the corresponding automation definition.

proxyMember is the TAutoProxy-derived class, the data type for the property.

options is a place to insert a hook, code to be called each time the automation command is executed. options can be omitted, but a comma must follow proxyMember anyway. For more details, see Automation Hook Macros.


AUTORECORD Macro

See also	Automation Hook Macros

Header File

ocf/automacr.h

Syntax

AUTORECORD(code)

Description

An automation server uses AUTORECORD in an automation declaration to hook in user-defined code that creates a record of each call made to a particular automation command. code is the expression or function call to execute on each command. It should store whatever information the application would need to play back the same command later.

Recording is not supported in the current version of ObjectComponents.


AUTOREPORT Macro

See also	Automation Hook Macros

Header File

ocf/automacr.h

Syntax

AUTOREPORT(code)

Description

An automation server uses AUTOREPORT in an automation declaration macro to hook in user-defined code that checks the error code from an automated member function. If code evaluates to 0, OLE assumes the command succeeded. If code evaluates to a nonzero value, then OLE throws an exception in the controller. Within the code expression, use Val to refer to the actual value returned.


AUTOARGS Macros

See also	Automation Proxy Macros

Header File

ocf/automacr.h

Description

An automation controller uses AUTOARGS to implement methods in its proxy objects. AUTOARGS macros list all the arguments that the controller passes to an automation command, identifying them by the dummy parameter names used in the function definition.

AUTOARGS macros are the second in three sets of macros used to implement methods in proxy objects. The first, AUTONAMES assigns names to any arguments that the controller wants to reference by name. The third set, AUTOCALL, tells whether the command is a method or a property and whether it returns a value.

Macro	Meaning

AUTOARGS0()	The automation command has no required arguments.

AUTOARGS1(a1)	The automation command requires argument a1.

AUTOARGS2(a1, a2)	The automation command requires arguments a1 and a2.

AUTOARGS3(a1, a2, a3)	The automation command requires arguments a1, a2, and a3.

The automacr.h header defines macros that accept up to ten arguments (AUTOARGS10). To generate versions that accept more arguments, use the MACROGEN.EXE utility.


AUTOCALL_xxxx Macros

See also	Automation Proxy Macros

Header File

ocf/automacr.h

Description

AUTOCALL is the third of three sets of macros that an automation controller uses to implement automation commands in proxy objects. The first two sets, AUTONAMES and AUTOARGS, describe the command's arguments. AUTOCALL macros tell whether the command represents a method or a property of the automated object and whether the command returns a value. Commands whose return value is itself an automated object must also be specially marked.

Macro	Meaning

AUTOCALL_METHOD_REF(prx)	The command is a method that returns a reference to an object. prx is an object derived from TAutoProxy and receives the return value.

AUTOCALL_METHOD_RET	The command is a method that returns a value.

AUTOCALL_METHOD_VOID	The command is a method that returns no value.

AUTOCALL_PROP_GET	The command returns the value of a property of the automated object.

AUTOCALL_PROP_REF(prx)	The command returns the value of a property and the value is itself an object. prx is an object derived from TAutoProxy and receives the return value.

AUTOCALL_PROP_SET(val)	The command assigns val to a property of the automated object.


AUTODATA Macros

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Description

An automation server uses AUTODATA macros in an automation declaration (after DECLARE_AUTOCLASS) to make data members of an automated class accessible through OLE.

Both forms take the same four parameters. name is the internal name that you assign to the data member. ObjectComponents uses the internal names to keep track of all the automated members. The only other place you use this name is in the subsequent automation definition (after DEFINE_AUTOCLASS).

member is the C++ name of the data member, the name you normally use in your source code.

In most cases, type should be a normal C++ data type, but if the data member is a string or an object then specify TAutoString or one of the TAutoObject classes instead. For more details, see Automation Data Types.

options is a place to insert a hook, code to be called each time the automation command is executed. Hooks can record, undo, or validate commands. options can be omitted, but a comma must follow the preceding argument anyway. For more details, see Automation Hook Macros.

Macro	Meaning

AUTODATA(name, member, type, options)	The command permits read and write access to a data member.

AUTODATARO(name, member, type, options)	The command permits read-only access to a data member.


DECLARE_AUTOAGGREGATE Macro

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Syntax

DECLARE_AUTOAGGREGATE(cls)

Description

DECLARE_AUTOAGGREGATE(cls) introduces the automation declaration for classes that are, inherit from, or delegate to Component Object Model (COM) objects.

The automation declaration declares automatable members of cls, a user-defined C++ class. It belongs with the declaration of cls. Be sure to use DEFINE_AUTOAGGREGATE in the corresponding automation definition.

The DECLARE_AUTOCLASS macro also introduces automation declarations. Use it for classes that are not, and do not inherit from or delegate to, COM objects.


DECLARE_AUTOCLASS Macros
DECLARE_AUTOCLASS Macro

See also	Automation Declaration Macros

Header File

ocf/automacr.h

Syntax

DECLARE_AUTOCLASS(cls)

Description

DECLARE_AUTOCLASS(cls) introduces a block of macros that declare automatable members of the user-defined class cls.

An automation server uses DECLARE_AUTOCLASS to begin a block of macros that make automatable members of a user-defined C++ class accessible to OLE. cls is the name of the user's C++ class.

The block of declaration macros usually appears in the definition of the automatable C++ class. A corresponding block of automation definition macros must appear in the implementation of the automatable C++ class.


DECLARE_COMBASESn Macros

See also

Header File

ocf/oleutil.h

Description

Use the COMBASES macros to create C++ objects that conform to the OLE Component Object Model (COM). COM objects support OLE interfaces and let you derive classes that interact with OLE directly, not through ObjectComponents. These macros are meant for advanced users.

COM objects are used as base classes for other objects. The derived class must inherit from both your COM class and from the ObjectComponents TUnknown class. TUnknown implements the controlling IUnknown interface for your object.

To create a COM class:

1.	Precede the declaration of the class with one of the DECLARE_COMBASES macros. Which you choose depends on how many interfaces (besides IUnknown) the COM class supports.

2.	Precede the implementation of your COM class with the corresponding DEFINE_COMBASES macro.

3.	Derive your final class multiply from TUnknown and your new COM class (in that order).

The first macro argument is name. It is the name of the COM class you are creating. i1, i2, i3, and i4 are the names of the interfaces your COM class supports.

Macro	Meaning

DECLARE_COMBASES1(name, i1)	Declare a COM class name that inherits from the i1 interface class.

DECLARE_COMBASES2(name, i1, i2) 	Declare a COM class name that inherits from the i1 and i2 interface classes.

DECLARE_COMBASES3(name, i1, i2, i3) 	Declare a COM class name that inherits from the i1. i2, and i3 interface classes.

DECLARE_COMBASES4(name, i1, i2, i3, i4) 	Declare a COM class name that inherits from the i1. i2, i3, and i4 interface classes.


DEFINE_AUTOAGGREGATE Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

DEFINE_AUTOAGGREGATE(cls, AggregatorFunction)

Description

An automation server uses DEFINE_AUTOAGGREGATE to begin a block of macros that define automatable members of cls, a user-defined C++ class. The block ends with the END_AUTOAGGREGATE macro.

The DEFINE_AUTOCLASS macro does the same thing but without the extra AggregatorFunction parameter. Use DEFINE_AUTOAGGREGATE when the C++ class you are automating is, inherits from, or delegates to a Component Object Model (COM) object. The AggregatorFunction parameter points to the aggregating function for reaching the COM object. For example, if Aggregate is the name of the COM object, the aggregater function might be any of these expressions:

Aggregate	// automated C++ object is the COM object

OcApp->Aggregate	// automated C++ object delegates to COM object

MyBase::Aggregate	// automated C++ object inherits from COM object

When the automation definition uses DEFINE_AUTOAGGREGATE, be sure to use DECLARE_AUTOAGGREGATE in the corresponding automation declaration.


DEFINE_AUTOCLASS Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

DEFINE_AUTOCLASS(cls)

Description

Introduces a block of macros in an automation server. Each macro in the block defines an automatable member of cls, a user-defined C++ class. The block ends with the END_AUTOCLASS macro.

The block of definition macros appears in the implementation of the automatable C++ class. A corresponding block of automation declaration macros must appear in the definition of the same class.


DEFINE_COMBASESn Macros

See also

Header File

ocf/oleutil.h

Description

Implements the IUnknown interface for each of the OLE interfaces that your COM object supports.

Use the COMBASE macros to create C++ objects that conform to the OLE Component Object Model (COM). COM objects support OLE interfaces and let you derive classes that interact with OLE directly, not through ObjectComponents. These macros are meant for advanced users.

Automated objects can delegate to COM objects using the DEFINE_AUTOAGGREGATE and the DECLARE_AUTOAGGREGATE macro.

To create a COM class:

1.	Precede the declaration of the class with one of the DECLARE_COMBASES macros. Which you choose depends on how many interfaces (besides IUnknown) the COM class supports.

2.	Precede the implementation of your COM class with the corresponding DEFINE_COMBASES macro.

3.	Derive your final class multiply from your new COM class and from TUnknown.

COM objects can delegate to other COM objects using another set of related macros also defined in oleutil.h. For more information, look in the header file for the DEFINE_QI_xxxx macros.

Macro	Meaning

DEFINE_COMBASES1(name, i1) 	Define IUnknown for the i1 interface in the COM class name.

DEFINE_COMBASES2(name, i1, i2) 	Define IUnknown for the i1 and i2 interfaces in the COM class name.

DEFINE_COMBASES3(name, i1, i2, i3)	Define IUnknown for the i1, i2, and i3 interfaces in the COM class name.

DEFINE_COMBASES4(name, i1, i2, i3, i4) 	Define IUnknown for the i1, i2, i3, and i4 interfaces in the COM class name.


END_AUTOAGGREGATE Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

END_AUTOAGGREGATE(cls, flags, name, doc, help)

Description

Terminates a block of macros that an automation server uses to define automatable methods in cls, a user-defined C++ class. The definition block begins with DEFINE_AUTOAGGREGATE Macro.

The related DEFINE_AUTOCLASS and END_AUTOCLASS macros also mark an automation definition block. Use the aggregation macros when cls is, inherits from, or delegates to a Component Object Model (COM) object.

name is the string that automation controllers use to identify objects of type cls. If the user asks OLE about the object name, the system returns the string in doc. If a .HLP file is registered for the object, then the context ID in help points to a screen that describes the object.

flags combines tfxxxx bit flags to provide type information for the automated class. The flags are documented with the END_AUTOCLASS macro.


END_AUTOCLASS Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

END_AUTOCLASS(cls, flags, name, doc, help)

Description

Terminates the block of macros an automation server uses to define automatable methods in cls, a user-defined C++ class. The definition block begins with DEFINE_AUTOCLASS.

name is the string that automation controllers use to identify objects of type cls. If the user asks OLE about the object name, the system returns the string in doc. If a .HLP file is registered for the object, then the context ID in help points to a screen that describes the object.

flags combines tfxxxx bit flags to provide type information for the automated class. Choose the flags that describe your class. The tfxxxx constants correspond to symbols defined by OLE and documented in OLE.HLP. The COCLASS, an OLE construct, holds type information for an OLE component, which might contain several smaller OLE objects. The COCLASS holds type information for all interfaces exposed at the component level.

Constant	Meaning

flags set on the COCLASS object

tfAppObject	TYPEFLAG_FAPPOBJECT, set on COCLASS

tfCanCreate	TYPEFLAG_FCANCREATE, set on COCLASS

tfLicensed	TYPEFLAG_FLICENSED, set on COCLASS

tfPredeclared	TYPEFLAG_FPREDECLID, set on COCLASS

tfControl	TYPEFLAG_FCONTROL, set on COCLASS

tfCoClassXfer	tfAppObject | tfCanCreate | tfLicensed | tfControl | tfPredeclared

flags set on the COCLASS interfaces

tfDefault	IMPLTYPEFLAG_FDEFAULT << 12

tfEventSource	IMPLTYPEFLAG_FSOURCE << 12

tfRestricted	IMPLTYPEFLAG_FRESTRICTED << 12

tfImplFlagXfer	tfDefault | tfEventSource | tfRestricted

flags set on individual automated classes

tfHidden	TYPEFLAG_FHIDDEN

tfNonextensible	TYPEFLAG_FNONEXTENSIBLE

tfAutoClassMask	tfHidden | tfNonextensible

flags defined by OLE, but not applicable to IDispatch interfaces

tfDual	TYPEFLAG_FDUAL

tfAutomation	TYPEFLAG_FOLEAUTOMATION

default flags for a class not exposed as part of the COCLASS

tfNormal	automated classes not at application level


EXPOSE_APPLICATION Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

EXPOSE_APPLICATION(cls, extName, doc, help)

Description

An automation server uses EXPOSE_APPLICATION in its automation definition (after DEFINE_AUTOCLASS macro) if it chooses to expose the application itself as a member of its automated object. OLE conventions suggest that each automation object should have this member.

cls is the class name of the application.

extName is the external, public name you assign to this member. Automation controllers use this string to refer to the application member. The string can be localized.

doc is a string that describes this member to the user. An automation controller can ask OLE for this string if the user requests help.

help is a context ID for an .HLP file. This parameter, which can be omitted, is useful only if you register an .HLP file to document your server. If you do, then when the user asks the controller for help, the controller passes this context ID to the Help system to display a screen describing the object member.


EXPOSE_DELEGATE Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

EXPOSE_DELEGATE(cls, extName, locator)

Description

An automation server uses EXPOSE_DELEGATE in its automation definition (after DEFINE_AUTOCLASS macro) in order to combine two unrelated C++ classes into a single OLE automation object. In effect, the application's primary automated class delegates some tasks to another automated class. This macro tells ObjectComponents to search both classes to determine what commands the automated OLE object can perform.

cls is the name of the auxiliary class, which must also be automated. In other words, it must contain its own automation declaration and definition.

extName is an external, public name that an OLE controller uses to refer to this member of the object.

locator is a function that returns a pointer to an auxiliary object. In order to call members of that class, ObjectComponents needs a pointer to an object of that type. The conversion function should follow this prototype:

auxclass *locator( autoclass *this );

where auxclass is the name of the auxiliary class and autoclass is the name of the primary automated class. locator in effect converts a this pointer to a that pointer.


EXPOSE_INHERIT Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

EXPOSE_INHERIT(cls, extName);

Description

An automation server uses EXPOSE_INHERIT in its automation definition (after DEFINE_AUTOCLASS) in order to combine two related C++ classes into a single OLE automation object. In effect, the application's primary automated class delegates some tasks to its base class. This macro tells ObjectComponents to search both classes to determine what commands the automated OLE object can perform.

cls is the name of the base class, which must also be automated. In other words, it must contain its own automation declaration and definition.

extName is an external, public name that an OLE controller uses to refer to this member of the object. It can be localized.


EXPOSE_ITERATOR Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

EXPOSE_ITERATOR(retType, doc, help);

Description

An automation server uses EXPOSE_ITERATOR in its automation definition (after DEFINE_AUTOCLASS) in order to expose an iterator object to enumerate objects in a collection. An iterator is useful only when the automated object itself represents a collection of other objects. The controller uses methods of the nested iterator object to retrieve and examine successive objects in a list.

retType is an automated data type that describes the type of the objects in the collection. For example, if the collection is an array of short integers, then retType should be TAutoShort. For more information, see Automation Data Types.

doc is a string that describes the iterator to the user. An automation controller can ask OLE for this string if the user requests help.

help is a context ID for an .HLP file. This parameter, which can be omitted, is useful only if you register an .HLP file to document your server. If you do, then when the user asks the controller for help, the controller passes this context ID to the Help system to display a screen describing the iterator.


EXPOSE_METHOD Macros

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

EXPOSE_METHOD(intName, retType, extName, doc, help);

EXPOSE_METHOD_ID(id, intName, retType, extName, doc, help);

Description

An automation server uses EXPOSE_METHOD macros in its automation definition (after DEFINE_AUTOCLASS) to expose a member function of an object to OLE for automation.

intName is an internal name that you assign to identify the method. ObjectComponents uses the internal name to keep track of all the automated members. This name must match the name assigned to the method with the AUTOFUNC macro in the automation declaration.

retType is a data type that describes the type of value the method returns. For example, if the method returns a long integer, then retType should be TAutoLong. For more information, see Automation Data Types.

extName is the external, public name that a controller uses to specify this method. The string can be localized.

doc is a string that describes this method to the user. An automation controller can ask OLE for this string if the user requests help. This string can also be localized.

help is a context ID for an .HLP file. This parameter, which can be omitted, is useful only if you register an .HLP file to document your server. If you do, then when the user asks the controller for help, the controller passes this context ID to the Help system to display a screen describing the method.

id is a dispatch identifier that you can choose to assign explicitly by using one of the EXPOSE_METHOD_ID macros. The dispatch ID is what OLE passes to identify commands requested by a controller. The OLE system header files define several standard dispatch ID values. For example, -5 is the default evaluation method. Standard dispatch IDs are always negative numbers. By default, dispatch IDs are assigned low positive numbers incremented from 1. If you want to specify explicit dispatch IDs for your applications, choose high positive values in order not to collide with the low positive numbers ObjectComponents assigns to exposed members without explicit IDs.

0 is the ID of the default method or property. ObjectComponents never automatically assigns 0 as a dispatch ID. To have a default method, you need to assign 0 yourself.

An EXPOSE_METHOD or EXPOSE_METHOD_ID macro must always be followed immediately by one macro for each of the method's arguments.

Type of Argument	Declaration Macro

Required	REQUIRED_ARG Macro

Optional	OPTIONAL_ARG Macro


EXPOSE_PROPxxxx Macros

See also	Automation Definition Macros

Header File

ocf/automacr.h

Description

An automation server uses EXPOSE_PROPxxxx macros in its automation definition (after DEFINE_AUTOCLASS) to expose properties of an object to OLE for automation. A property is data that can be read or written only through a set of access functions (for example, GetPosition and SetPosition.)

Macro	Meaning

EXPOSE_PROPRW(intName, type, extName, doc, help)	The property can be read and written.

EXPOSE_PROPRW_ID(id, intName, type, extName, doc, help)	The property can be read and written. Its dispatch ID is id.

EXPOSE_PROPRO(intName, type, extName, doc, help)	The property is read-only.

EXPOSE_PROPRO_ID(id, intName, type, extName, doc, help)	The property is read-only. Its dispatch ID is id.

EXPOSE_PROPWO(intName, type, extName, doc, help)	The property is write-only and cannot be read (rarely used).

intName is an internal name that you assign to identify the property. ObjectComponents uses the internal name to keep track of all the automated members. This name must match the name assigned to the method with the AUTOPROP macro in the automation declaration.

type is a data type that describes the type of value the property holds. For example, if the property is a string, then type should be TAutoString. For more information, see Automation Data Types.

extName is the public name that a controller uses to refer to this property. The string can be localized.

doc is a string that describes this property to the user. An automation controller can ask OLE for this string if the user requests help. This string can also be localized.

help is a context ID for an .HLP file. This parameter, which can be omitted, is useful only if you register an .HLP file to document your server. If you do, then when the user asks the controller for help, the controller passes this context ID to the Help system to display a screen describing the property.

id is a dispatch identifier that you can choose to assign explicitly by using one of the EXPOSE_xxxx_ID macros. The dispatch ID is what OLE passes to identify commands requested by a controller. The OLE system header files define several standard dispatch ID values. For example, -5 is the default evaluation method. Standard dispatch IDs are always negative numbers. By default, dispatch IDs are assigned low positive numbers incremented from 1. If you want to specify explicit dispatch IDs for your applications, choose high positive values in order not to collide with the low positive numbers ObjectComponents assigns to exposed members without explicit IDs.

0 is the ID of the default method or property. ObjectComponents never automatically assigns 0 as a dispatch ID. To have a default property, you need to assign 0 yourself.

Note:	A potential ambiguity arises in the type parameter when a read/write property contains an automated object. In the property setting function, type describes an argument, but in the property getting function, it describes a return value. According to the table of Automation Data Types, the value of the type parameter should be TAutoObject<> for a function argument and TAutoObjectDelete<> for a return value. In such cases, specify TAutoObjectDelete<> for type. ObjectComponents ignores the deletion information for the argument of the property setting function.


EXPOSE_QUIT Macro

See also	Automation Definition Macros

Header File

ocf/automacr.h

Syntax

EXPOSE_QUIT(extName, docString, helpContext)

Description

An automation server that exposes the application itself as an automated object uses the EXPOSE_QUIT macro to make a safe shutdown method available to the controller. The shutdown method implemented by this macro checks whether the application was originally invoked by OLE for automation. If so, it unregisters the active object and shuts down the server. If the user invoked the server before the controller connected to it, however, then the shutdown method does nothing because the application should continue to run.

Every automated application should include EXPOSE_QUIT in the application object's automation definition (after DEFINE_AUTOCLASS). EXPOSE_QUIT is not needed in the automation definition of other automated objects the server might create.

extName is the external, public name that a controller uses to call this method. The string can be localized.

doc is a string that describes the shutdown method to the user. An automation controller can ask OLE for this string if the user requests help. This string can also be localized.

help is a context ID for an .HLP file. This parameter, which can be omitted, is useful only if you register an .HLP file to document your server. If you do, then when the user asks the controller for help, the controller passes this context ID to the Help system to display a screen describing the shutdown method.


OPTIONAL_ARG Macro

See also

Header File

ocf/automacr.h

Syntax

OPTIONAL_ARG(cls, extName, default)

Description

An automation server uses this macro in its automation definition (after DEFINE_AUTOCLASS) in order to describe one argument in an exposed method.

After an EXPOSE_METHOD or EXPOSE_METHOD_ID macro, you need to add a list of argument macros, one for each parameter in the method. If the argument has a default value, then use the OPTIONAL_ARG macro.

type is an automation class that describes the argument's data type. For example, if the argument is Boolean value, then type should be TAutoBool. For more information, see Automation Data Types.

extName is the public name that a controller uses to refer to this argument. The string can be localized.

default is the default value assigned if the caller chooses to omit the argument.


REQUIRED_ARG Macro

See also

Header File

ocf/automacr.h

Syntax

REQUIRED_ARG(type, extName);

Description

An automation server uses this macro in its automation definition (after DEFINE_AUTOCLASS) in order to describe one argument in an exposed method.

After an EXPOSE_METHOD or EXPOSE_METHOD_ID macro, you need to add a list of argument macros, one for each parameter in the method. If the argument does not have a default value and is not an object, then use the REQUIRED_ARG macro.

type is an automation class that describes the argument's data type. For example, if the argument is Boolean value, then type should be TAutoBool. For more information, see Automation Data Types.

extName is the external, public name that a controller uses to refer to this argument. The string can be localized.


HR_xxxx Return Constants

General OLE Classes, Macros, and Type Definitions

Header File

ocf/ocdefs.h

Description

OLE system calls return HRESULT values that sometimes encode detailed information about the result of the call. ObjectComponents sometimes passes HRESULT values back to you. These macros simplify the task of testing for some common results. Each represents a possible return value. For a complete listing of HRESULT return values, see the scode.h header file.

Constant	Meaning

HR_ABORT	The operation was aborted.

HR_FAIL	An unspecified error occurred.

HR_FALSE	An action did not complete in the usual way but no error occurred. For example, an enumeration reached the end of its list.

HR_HANDLE	A handle is invalid.

HR_INVALIDARG	One or more arguments are invalid.

HR_NOERROR	No error occurred.

HR_NOINTERFACE	The requested interface is not supported.

HR_NOTIMPL	The requested service is not implemented.

HR_OK	Same as HR_NOERROR.

HR_OUTOFMEMORY	Not enough memory is available to complete the operation.

HR_POINTER	A pointer is invalid.


TOcFormatName class

See also	Linking and Embedding Classes

Header File

ocf/ocapp.h

Description

TOcApp uses this class internally to hold the strings that describe a Clipboard data format such as text or bitmap. TOcApp displays these strings in standard OLE dialog boxes such as Paste Link.

Every Clipboard format has three associated pieces of information: an ID value, a name string, and a result name. For standard formats, the ID is a constant such as CF_SYLK. The name string is a short name such as "Sylk." The result name is a longer string that tells the user what pasting this data produces -- for example, "a spreadsheet". A TOcFormatName object holds all three values for one format.

TOcApp makes a TOcNameList object to hold all the format names it needs. It loads descriptive strings into TOcFormatName objects and adds the objects one by one to its name list. Both objects are created and managed inside TOcApp. Usually you do not have to manipulate either of them directly.

Public Constructor and Destructor

TOcFormatName

~TOcFormatName

Public Member Functions

operator ==

GetId

GetName

GetResultName


TOcFormatName::TOcFormatName

TOcFormatName

Syntax 1

TOcFormatName();

Description

Constructs an empty format name object.

Syntax 2

TOcFormatName(const char far* fmtName, const char far* fmtResultName, const char far* id = 0);

Description

Constructs a format name object and initializes it with three values that describe a Clipboard format. fmtName is the name of the format ("metafile"). fmtResultName describes what the user gets by pasting this format ("a Windows metafile picture"). id is the value that Windows assigns to identify the format (CF_METAFILEPICT) but expressed as a string of decimal digits ("3").

Destructor

~TOcFormatName();

Description

Releases the object.


TOcFormatName::operator ==

TOcFormatName

Syntax

bool operator ==(const TOcFormatName& other) const;

Description

Returns true if other is the same object as this.


TOcFormatName::GetId

TOcFormatName

Syntax

const char far* GetId() const;

Description

Returns a pointer to the string that the system uses to designate the format.


TOcFormatName::GetName

TOcFormatName

Syntax

const char far* GetName() const;

Description

Returns a pointer to the name of the format.


TOcFormatName::GetResultName

TOcFormatName

Syntax

const char far* GetResultName() const;

Description

Returns the descriptive string that tells the user what pasting data of this format produces.


TOcNameList class

See also	Linking and Embedding Classes

Header File

ocf/ocapp.h

Description

TOcApp uses this class internally to manage a collection of TOcFormatName. Each format name object holds three strings that describe a Clipboard data format such as text or bitmap. TOcApp displays these strings in standard OLE dialog boxes such as Paste Link.

The list of format names is created and managed inside TOcApp. Usually you do not have to manipulate the list directly. To put your own custom formats in the list, however, you do have to register them. See TOcApp::AddUserFormatName for more information about setting up custom formats.

Standard Windows Clipboard formats are always added to the list for you. The name and result strings for standard formats are defined in OLEVIEW.RC. To localize the strings, edit this file. (Standard formats do not have an identifier string. Instead they have a registration number, such as CF_TEXT.)

Public Constructor and Destructor

TOcNameList

~TOcNameList

Public Member Functions

operator []

operator []

Add

Clear

Count()

Detach

Find

IsEmpty


TOcNameList::TOcNameList

See also	TOcNameList

Constructor Syntax

TOcNameList();

Description

Constructs a name list containing no items. To insert names in the list, call Add.

Destructor Syntax

~TOcNameList();

Description

Destroys the list and the objects in the list.


TOcNameList::operator []

See also	TOcNameList

Syntax (Form 1)

TOcFormatName*& operator[](unsigned index);

Description

Returns the item at position index in the list of format name objects. The first object is at index 0. If index points past the end of the list, the function throws a precondition exception.

Syntax (Form 2)

TOcFormatName* operator[](char far* id);

Description

Returns the format name object whose format ID string matches id. The return value is 0 if no match is found.


TOcNameList::Add

See also	TOcNameList

Syntax

int Add(TOcFormatName* name);

Description

Inserts the object name into the list. Returns 1 for success and 0 for failure.


TOcNameList::Clear

See also	TOcNameList

Syntax

void Clear(int del = 1);

Description

Empties the list. If del is 1, Clear also deletes each object in the list.


TOcNameList::Count

See also	TOcNameList

Syntax

virtual uint Count() const;

Description

Returns the number of items in the list.


TOcNameList::Detach

See also	TOcNameList

Syntax

int Detach(const TOcFormatName* name, int del = 0);

Description

Removes the single object name from the list. If del is 1, Detach also deletes the object name.


TOcNameList::Find

TOcNameList

Syntax

unsigned Find(const TOcFormatName* name) const;

Description

Searches the list and returns the position of name. If the name object is not in the list, Find returns UINT_MAX.


TOcNameList::IsEmpty

See also	TOcNameList

Syntax

int IsEmpty() const;

Description

Returns 1 if the list currently contains no items and 0 if it contains at least one item.


TOcRegistrar class

See also	Linking and Embedding Classes

Header File

ocf/ocapp.h

Base Class

TRegistrar

Description

TOcRegistrar manages all the registration tasks for an application. It processes OLE-related switches on the command line and records any necessary information about the application in the system registration database. If the application is already registered in the database, the registrar confirms that the registered path, progid, and clsid are still accurate. If not, it reregisters the application.

Every ObjectComponents application needs to create a registrar object. If your application supports linking and embedding, then create a TOcRegistrar object. If your application supports automation but not linking and embedding, then you should create a TRegistrar object instead. TOcRegistrar extends TRegistrar by connecting the application to the BOCOLE support library interfaces that support linking and embedding.

An application's main procedure usually performs these actions with its registrar:

Construct the registrar, passing it a pointer to the application's factory callback.

Call IsOptionSet to check for options that might affect how the application chooses to start (for example, remaining invisible if invoked for embedding.

Call Run to enter the program's message loop.

TOcRegistrar inherits both IsOptionSet and Run from its base class, TRegistrar.

Public Constructor and Destructor

TOcRegistrar

~TOcRegistrar

Public Member Functions

CreateOcApp

CreateOcApp

Protected Member Functions

CanUnload

GetFactory

LoadBOle


TOcRegistrar::TOcRegistrar

See also	TOcRegistrar

Constructor Syntax

TOcRegistrar(TRegList& regInfo, TComponentFactory callback, string& cmdLine, TRegLink* linkHead = 0, HINSTANCE hInst = ::_hInstance);

Description

regInfo is the application registration structure (conventionally named appReg).

callback is the factory callback function that ObjectComponents invokes when it is time for the application to create an object. An ObjectWindows program can use the TOleFactory class to implement this callback. For a description of TOleFactory, see Factory Template Classes and TOleFactoryBase.

cmdLine holds the command line string that invoked the application.

hInst is the application's instance.

Destructor Syntax

~TOcRegistrar();

Description

Destroys objects the registrar uses internally.


TOcRegistrar::CreateOcApp

See also	TOcRegistrar

Syntax

void CreateOcApp(uint32 options, TOcApp*& ret);

void CreateOcApp(uint32 options, TOcAppHost* host, TOcAppFrameHost* frameHost);

Description

Creates the connector object that attaches an application to OLE. options is a set of bit flags indicating the application's running mode. The possible option flags are defined in TOcAppMode. ret is where CreateOcApp places a pointer to the newly created TOcApp connector object.

CreateOcApp is called during TOcAppHost::OcInit. You shouldn't have to call it directly yourself.

The purpose of CreateOcApp is to shield you from the details of the TOcApp connector object. TOcApp is closely tied to the implementation of ObjectComponents, and the details of initializing an OLE session are subject to change.


TOcRegistrar::CanUnload

TOcRegistrar

Syntax

bool CanUnload();

Description

Returns true if the application is not currently serving any OLE clients and false otherwise.


TOcRegistrar::GetFactory

TOcRegistrar

Syntax

void far* GetFactory(const GUID& clsid, const GUID far& iid);

Description

Returns a pointer to the factory interface for creating the type of object indicated by clsid. iid  names the particular interface you want to receive. If the registrar is unable to find an iid interface for clsid objects, it returns zero.

ObjectComponents calls a DLL's GetFactory member every time a new client loads the DLL. Usually you do not need to call GetFactory yourself.


TOcRegistrar::LoadBOle

TOcRegistrar

Syntax

void LoadBOle();

Description

Loads and initializes the ObjectComponents support library (BOCOLE.DLL). LoadBOle throws a TXObjComp exception if it cannot find OCOLE.DLL, or if the installed version is not compatible with the application's version of the library.


TOcApp class

See also	Linking and Embedding Classes

Header File

ocf/ocapp.h

Base Class

TUnknown

Description

TOcApp is an ObjectComponents connector object for a linking and embedding application. It implements the interfaces an application needs for communicating with OLE. Any ObjectComponents application that supports linking and embedding needs to have a TOcApp object. Usually the registrar creates it for you when you call TOcRegistrar->Run.

Applications that support automation but do not support linking and embedding do not need a TOcApp object. They create a TRegistrar instead of a TOcRegistrar.

TOcApp is a COM object and implements the IUnknown interface.

Public Constructor and Destructor

TOcApp

~TOcApp

Public Member Functions

AddUserFormatName

Browse

BrowseClipboard

BrowseControls

CanClose

Clip

Convert

Copy

Copy

Drag

Drag

EnableEditMenu

EvActivate

EvResize

EvSetFocus

GetName

GetNameList

GetRegistrar

IsOptionSet

ModalDialog

Paste

RegisterClass

RegisterClasses

ReleaseObject

SetOption

SetupWindow

TranslateAccel

UnregisterClass

UnregisterClasses

Protected Data Members

FrameHost

Host

OcAppPtr

Options

Registered


TOcApp::TOcApp

See also	TOcApp

Constructor Syntax

TOcApp(TOcRegistrar& registrar, uint32 options, TOcAppHost* host, TOcAppFrameHost* frameHost);

Description

The constructor for a TOcApp object expands the application's message queue if necessary to accommodate OLE message traffic and builds the application's list of supported Clipboard formats.

registrar is a registration object that processes the command line. Create the registrar first.

options is a set of application mode bit flags. The TOcApp object is usually created in the TComponentFactory callback function. The constructor's options parameter is the same as the callback's options parameter.

host is an object that handles messages sent by the TOcApp object.

frameHost is an object that calls the OLE memory allocator for the TOcApp object, creates the TOcAppHost object, and releases the objects when the application quits.

Destructor Syntax (Private)

~TOcApp();

Description

The TOcApp destructor notifies OLE that the application is no longer available.

Note	Usually the creation and destruction of an application's TOcApp object are managed by the TOcRegistrar object.


TOcApp::AddUserFormatName

See also	TOcApp

Syntax

void AddUserFormatName(const char far* name, const char far* resultName, const char far* id = 0);

Description

Call this function to associate a result name with a Clipboard format. The resultName parameter describes the data format to users and appears in Help text of the Paste Special dialog box. Use one of the other two parameters to identify the associated Clipboard format. This method is used only if you have a non-standard, private Clipboard format that you want to associate with names used in the Paste Special dialog box.

A custom format must first be entered in the application's registration tables using the REGFORMAT macro. For example:

REGFORMAT(0, "DrawingClip", ocrContent, ocrIStorage, ocrGet);

"DrawingClip" becomes the ID string that Windows uses internally to identify the custom format. To associate more descriptive strings with the custom format, call AddUserFormatName:

AddUserFormatName("DrawingPad", "a freehand drawing", "DrawingClip");

The name of the "DrawingClip" format is now "DrawingPad". If the user chooses Paste Special when data of this type is on the Clipboard, the name in the dialog box is "DrawingPad". It is perfectly legal for the ID and the name to be the same string.

The result string, "a freehand drawing", typically appears in the Help text during a Paste Special operation.


TOcApp::Browse

See also	TOcApp

Syntax

bool Browse(TOcInitInfo& initInfo);

Description

Displays the Insert Object dialog box allowing the user to choose from available servers to create a new object in the open document. Returns true if the user inserts an object and false if the user cancels.

Create initInfo first by passing to its constructor the view object where the new object will be inserted. Browse fills initInfo with information about the object. Then use initInfo to create a new TOcPart.


TOcApp::BrowseClipboard

See also	TOcApp

Syntax

bool BrowseClipboard(TOcInitInfo& initInfo);

Description

Displays the Paste Special dialog box showing the available formats for the data currently on the Clipboard, allowing the user to choose what format to paste. Returns true if the user pastes data and false if the user cancels.

Create initInfo first by passing to its constructor the view object where the new object will be inserted. Browse fills initInfo with information about the object. Then use initInfo to create a new TOcPart.

This function is called by TOcView::BrowseClipboard.


TOcApp::BrowseControls

TOcApp

Syntax

bool BrowseControls(TOcInitInfo& InitInfo);

Description

Displays the Insert Control dialog box, allowing the user to choose a control to embed in the open document. Returns true if the user inserts a control. Returns false otherwise.


TOcApp::CanClose

TOcApp

Syntax

bool CanClose();

Description

A container calls this function to determine whether it can shut down. CanClose polls all the connected servers and attempts to close them. It returns true if it is safe to close the application.


TOcApp::Clip

See also	TOcApp

Syntax

bool Clip(IBPart far* part, bool link, bool embed, bool delay = false);

Description

Copies the currently selected object to the Clipboard. Usually you do not have to call Clip directly because TOcView::Copy does it for you.

part points to the linked or embedded object. You can pass an object of type TOcPart for this parameter. (TOcPart supports the IBPart interface, which is defined in the BOCOLE library.) If link and embed are both true, then other applications can either link or embed the object when they paste it from the Clipboard. Make delay true to have ObjectComponents provide delayed rendering of alternate data formats. (Delayed rendering saves memory. For more information, refer to the Clipboard Overview in the API Help file. Look for the topic "Clipboard Operations.")


TOcApp::Convert

See also	TOcApp

Syntax

bool Convert(TOcPart* ocPart, bool activate);

Description

Displays the Convert dialog box where the user can alter the aspect or format of a linked or embedded object. ocPart points to the object the user wants to modify.

Make activate true if you want ObjectComponents to activate the object after converting it. Generally activate should be false if the user has chosen Links from the Edit menu. If the user tries to activate an object whose server is not present, you can offer the option of converting the object to another server, and in that case activate should be true.


TOcApp::Copy

See also	TOcApp

Syntax 1

bool Copy(TOcPart* ocPart);

Description

Copies a TOcPart object, such as an OLE object or an OCX control.

Syntax 2

bool Copy(TOcDataProvider* ocData);

Description

Copies a TOcDataProvider item, such as part of an object.


TOcApp::Drag

See also	TOcApp

Syntax 1

bool Drag(TOcDataProvider* ocData, TOcDropAction inAction, TOcDropAction& outAction);

Syntax 2

bool Drag(TOcPart* ocData, TOcDropAction inAction, TOcDropAction& outAction);

Description

A container calls this function when the user wants to drag one of the container's objects.

ocData is a TOcDataProvider or TOcPart object.

inAction combines bit flags indicating possible drag actions the application supports. The flags indicate whether the user can move, copy, or link the object.

outAction contains just one of the action flags indicating what actually did happen.


TOcApp::EnableEditMenu

See also	TOcApp

Syntax

uint EnableEditMenu(TOcMenuEnable enable, IBDataConsumer far* ocview);

Description

An application calls EnableEditMenu to find out which of the OLE-related commands on its Edit menu should currently be enabled. The flags combined in enable indicate the commands to be tested, and the return value uses the same bit flags to indicate which commands to enable. ocview is usually an object of type TOcView. (TOcView supports the IBDataConsumer interface, which is defined in the BOCOLE library.)

TOleWindow and TOleView call TOcMenuEnable enum in the command enabler functions for the Edit menu.


TOcApp::EvActivate

See also	TOcApp

Syntax

void EvActivate(bool active);

Description

A container calls this function to tell OLE when its frame window becomes active or inactive. Make active true if the window was activated or false if it was deactivated.


TOcApp::EvResize

See also	TOcApp

Syntax

void EvResize();

Description

A container calls this function to tell OLE when the size of its frame window (the main window) has changed. OLE might need this information to let a server modify its tool bar during in-place editing.


TOcApp::EvSetFocus

See also	TOcApp

Syntax

bool EvSetFocus(bool set);

Description

A container calls this function to tell OLE that its frame window has either received or yielded the input focus. Make set true if the window gained the focus or false if it lost the focus.


TOcApp::GetName

TOcApp

Syntax

string GetName() const;

Description

Returns a string object containing the application's name.


TOcApp::GetNameList

See also	TOcApp

Syntax

TOcNameList& GetNameList();

Description

Returns an array of TOcNameList objects containing the names of all the Clipboard formats the application supports. The TOcView class uses this list when executing the Paste Special command. The list provides the names and Help strings associated with the formats.


TOcApp::GetRegistrar

See also	TOcApp

Syntax

TOcRegistrar& GetRegistrar();

Description

Returns the application's registrar object. This is the same object passed into the TOcApp constructor.


TOcApp::IsOptionSet

See also	TOcApp

Syntax

bool IsOptionSet(uint32 option) const;

Description

Tests the application mode flags and returns true if those set in option are set for the application. The application mode flags are defined in the TOcAppMode enum.

Registrar objects also have an IsOptionSet method. In most cases the two return the same results. In a DLL server, however, the registrar remembers the set of options that the server originally started with, while TOcApp::IsOptionSet queries the options for the currently active instance of the DLL.

To check options in a linking and embedding application, you should call the IsOptionSet member your application object inherits from TOcAppHost. TOcAppHost::IsOptionSet calls TOcApp::IsOptionSet.

A automation DLL server that does not support linking and embedding does not have a TOcApp object. It can, however, still find its per-instance options by examining the option flags passed to its factory callback.


TOcApp::ModalDialog

TOcApp

Syntax

bool ModalDialog(bool enable);

Description

Specifies whether or not the dialog box is modal.


TOcApp::Paste

See also	TOcApp

Syntax

bool Paste(TOcInitInfo& initInfo);

Description

Fills initInfo with information about the object on the Clipboard. Returns true if it succeeds in gathering information and false if it fails. The information is needed to create a new TOcPart object.

TOcApp::Paste is called by TOcView::Paste. Usually you don't need to call TOcApp::Paste directly yourself.


TOcApp::RegisterClass

See also	TOcApp

Syntax

bool RegisterClass(const string& progid, BCID classId, bool multiUse);

Description

Tells OLE that the application is capable of producing objects of a certain type. What objects a server can produce depend on the types of documents it registers.

progid is the registered string that identifies a type of object.

RegisterClasses loops through the application's document templates and calls RegisterClass once for each type. The call is made internally and usually you do not need to invoke either function directly.


TOcApp::RegisterClasses

See also	TOcApp

Syntax

void RegisterClasses(const TDocTemplate* tplHead = ::DocTemplateStaticHead);

Description

Announces to OLE that the application is running and tells OLE about each type of document the application has registered. The document types are exposed to OLE as kinds of objects the application can produce. RegisterClasses tells OLE who you are and what you can make.

tplHead points to the beginning of the application's list of document templates. ObjectWindows stores this list in the global variable DocTemplateStaticHead. UnregisterClasses loops through the list of document types and calls UnregisterClass for each one that has a registered progid.

RegisterClasses loops through the document structures in tplHead and calls RegisterClass once for each type that has a progid. The call is made internally, and usually you do not need to invoke either function directly.


TOcApp::ReleaseObject

See also	TOcApp

Syntax

virtual void ReleaseObject();

Description

ReleaseObject notifies the object that the application's main window is gone. If the application is not serving a client, ReleaseObject also decrements the TOcApp object's internal reference count. The object will destroy itself when the count reaches zero. The destructor of TOcAppHost calls this function.


TOcApp::SetOption

See also	TOcApp

Syntax

void SetOption(uint32 bit, bool state);

Description

Modifies the application's running mode flags. bit contains bit flags from the TOcAppMode enum. If state is true, SetOption turns the flags on. If state is false, it turns the flags off. You should never have to call this function because ObjectComponents always maintains the mode flags.


TOcApp::SetupWindow

TOcApp

Syntax

void SetupWindow(TOcAppFrameHost* frameHost);

Description

Tells the TOcApp object what object to associate with the application's main window.


TOcApp::TranslateAccel

TOcApp

Syntax

bool TranslateAccel(MSG far* msg);

Description

A container application adds TranslateAccel to its Windows message loop if it wants to make a DLL server's accelerator keystrokes available to the user during in-place editing. DLL servers require this cooperation because they do not have message loops of their own, as an .EXE server does.

If you call TranslateAccel after the usual call to the Windows API TranslateAccelerator, then your own accelerators will have priority if they happen to conflict with the server's.

msg holds a Windows message structure. The return value is true if the server translates the accelerator and false if it does not.


TOcApp::UnregisterClass

See also	TOcApp

Syntax

bool UnregisterClass(const string& progid);

Description

Notifies OLE when the application is no longer available to produce objects of a certain type. progid is the registered string that identifies a type of object.

UnregisterClasses loops through all the documents the application registered and calls UnregisterClass for each one. The destructor of TOcApp calls UnregisterClasses.


TOcApp::UnregisterClasses

See also	TOcApp

Syntax

void UnregisterClasses(const TDocTemplate* tplHead = ::DocTemplateStaticHead);

Description

Announces to the system that the application is no longer available for OLE interactions. tplHead points to the beginning of the application's list of document templates. ObjectWindows stores this list in the global variable DocTemplateStaticHead.

UnregisterClasses loops through the list of document types and calls UnregisterClass for each one that has a registered progid. UnregisterClasses is called from the TOcApp destructor.


TOcApp::FrameHost

See also 	TOcApp

Syntax

TOcAppFrameHost* FrameHost;

Description

The TOcAppFrameHost object associated with the TOcApp object.


TOcApp::Host

See also 	TOcApp

Syntax

TOcAppHost* Host;

Description

The TOcAppHost object associated with the TOcApp object.


TOcApp::OcAppPtr

TOcApp 	TOcApp

Syntax

TOcApp** OcAppPtr;

Description

A pointer to a pointer to the TOcApp object.


TOcApp::Options

See also 	TOcApp

Syntax

uint32 Options;

Description

The options for the TOcApp object.


TOcApp::Registered

TOcApp

Syntax

bool Registered;

Description

A Boolean value indicating whether the TOcApp object is registered in the system’s OLE registration database.


TOcGetAccel struct

Header File

ocf/ocapp.h

Description

Structure for a keyboard accelerator.

Data Members

Accel

Count


TOcGetAccel::Accel

TOcGetAccel

Syntax

HACCEL Accel;

Description

The keyboard accelerator.


TOcGetAccel::Count

TOcGetAccel

Syntax

int Count;

Description

The number of times the accelerator was pressed.


TOcAppHost class

See also

Header File

ocf/ocapp.h

Description

Used to create and release a TOcApp object.

Public Constructor and Destructor

TOcAppHost

~TOcAppHost

Public Member Functions

AttachHost

GetRegistrar

IsOptionSet

OcInit

ReleaseOcObject

Protected Members

OcApp

OLEMalloc


TOcAppHost::TOcAppHost

TOcAppHost

Constructor Syntax

TOcAppHost();

Description

Creates a TOcAppHost object.

After you create the TOcAppHost object, call its OcInit member function.

Destructor Syntax

~TOcApp();

Description

Releases the TOcAppHost object.


TOcAppHost::AttachHost

TOcAppHost

Syntax

virtual void AttachHost(TOcApp* ocApp);

Description

Stores a pointer to a TOcApp object in the OcApp data member. Normally, this assignment occurs automatically when you call TOcAppHost::OcInit.


TOcAppHost::GetRegistrar

TOcAppHost

Syntax

TRegistrar& GetRegistrar();

Description

Returns the application’s TRegistrar object.


TOcAppHost::IsOptionSet

TOcAppHost

Syntax

bool IsOptionSet(uint32 option) const;

Description

Returns whether a particular option is set for the application. option can be any constant defined in the TOcAppMode enum.


TOcAppHost::OcInit

TOcAppHost

Syntax

void OcInit(TOcRegistrar& registrar, uint32 options);

Description

Creates an OLE memory allocator object and a TOcApp object.

registrar is the TOcRegistrar object for the application. (Create the TOcRegistrar object before calling TOcAppHost::OcInit.)

options are the application’s running modes as defined in the TOcAppMode enum.


TOcAppHost::ReleaseOcObject

TOcAppHost

Syntax

virtual void ReleaseOcObject();

Description

Releases the application’s TOcApp object and sets the OcApp data member to zero.


TOcAppHost::OcApp

TOcAppHost

Syntax

TOcApp* OcApp;

Description

A pointer to the application’s TOcApp object. The object is created automatically when you call TOcAppHost::Init.


TOcAppHost::OLEMalloc

TOcAppHost

Syntax

TOLEAllocator OLEMalloc;

Description

The application’s OLE memory allocator object. The object is created automatically when you call TOcAppHost::Init.


TOcAppFrameHost class

TOcAppHost

Header File

ocf/ocapp.h

Description

A class that contains virtual functions that correspond to each of the ObjectComponents events that are handled at the application level. You control how an application responds to the ObjectComponents events by implementing the virtual functions.

In the previous version of ObjectComponents, you handled ObjectComponents events in the main window procedure. However, with the new method -- handling ObjectComponents events by implementing the virtual functions of a message-handling class -- you can more easily debug your applications since you can trace execution into the virtual functions.

If you want to use the old method of handling application-level ObjectComponents events, use the TOcAppFrameHostMsg.

Public Constructor and Destructor

TOcAppFrameHost

Public Member Functions

EvOcAppBorderSpaceReq

EvOcAppBorderSpaceSet

EvOcAppDialogHelp

EvOcAppFrameRect

EvOcAppGetAccel

EvOcAppInsMenus

EvOcAppMenus

EvOcAppProcessMsg

EvOcAppRestoreUI

EvOcAppShutdown

EvOcAppStatusText

EvOcGetWindow

ReleaseOcObject

Protected Data Members

OcApp


TOcAppFrameHost::TOcAppFrameHost

TOcAppFrameHost

Constructor Syntax

TOcAppFrameHost(TOcApp* ocApp = 0)

Description

Creates a TOcAppFrameHost object and attaches it to the application’s TOcApp object. (Create the TOcApp object first using the TOcAppHost class.)


TOcAppFrameHost::EvOcAppBorderSpaceReq

TOcAppFrameHost

Syntax

virtual bool EvOcAppBorderSpaceReq(TRect far* rect);

Description

Responds to an OC_APPBORDERSPACEREQ message sent to a container. The response is whether or not the container can give border space in its frame window to the server.


TOcAppFrameHost::EvOcAppBorderSpaceSet

TOcAppFrameHost

Syntax

virtual bool EvOcAppBorderSpaceSet(TRect far* rect);

Description

Responds to an OC_APPBORDERSPACESET message by making room in the container's frame window for the border space that the server has requested.


TOcAppFrameHost::EvOcAppDialogHelp

TOcAppFrameHost

Syntax

virtual bool EvOcAppDialogHelp(TOcDialogHelp far& dh);

Description

Responds to an OC_APPDIALOGHELP message. The dh parameter refers to one of the TOcDialogHelp enum constants that indicate the kind of dialog box the user has open. For example, dhBrowseLinks indicates that the Links dialog box is open. The TOcDialogHelp enum lists the help constants and their dialog box equivalents.


TOcAppFrameHost::EvOcAppFrameRect

TOcAppFrameHost

Syntax

virtual bool EvOcAppFrameRect(TRect far* rect) = 0;

Description

Responds to an OC_APPFRAMERECT message sent to a container. The response is to get the coordinates of the client area rectangle of the application's main window.


TOcAppFrameHost::EvOcAppGetAccel

See also

Syntax

virtual bool EvOcAppGetAccel(TOcGetAccel far* acc) = 0;

Description

Sends the OC_APPGETACCEL message to the application’s main window, forwarding the accelerator in acc.


TOcAppFrameHost::EvOcAppInsMenus

TOcAppFrameHost

Syntax

virtual bool EvOcAppInsMenus(TOcMenuDescr far& sharedMenu;

Description

Responds to an OC_APPINSMENUS message by merging the container's menu into the shared menu. The sharedMenu parameter refers to this merged menu.


TOcAppFrameHost::EvOcAppMenus

TOcAppFrameHost

Syntax

virtual bool EvOcAppMenus(TOcMenuDescr far& md) = 0;

Description

Responds to an OC_OCAPPMENUS sent to the container. The response is to install a merged menu bar.


TOcAppFrameHost::EvOcAppProcessMsg

TOcAppFrameHost

Syntax

virtual bool EvOcAppProcessMsg(MSG far* msg) = 0;

Description

Responds to an OC_APPROCESSMSG message sent to the container asking the server to process accelerators and other messages from the container's message queue.


TOcAppFrameHost::EvOcAppRestoreUI

TOcAppFrameHost

Syntax

virtual bool EvOcAppRestoreUI() = 0;

Description

Responds to an OC_APPRESTOREUI message by restoring the container's normal menu and borders because in-place editing has finished.


TOcAppFrameHost::EvOcAppShutdown

TOcAppFrameHost

Syntax

virtual bool EvOcAppShutdown() = 0;

Description

Responds to an OC_APPSHUTDOWN message indicating that the last embedded object has been closed. The response is to shut down the server.


TOcAppFrameHost::EvOcAppStatusText

TOcAppFrameHost

Syntax

virtual bool EvOcAppStatusText(const char far* rect) = 0;

Description

Responds to an OC_APPSTATUSTEXT message by displaying text from the server on this container's status bar.


TOcAppFrameHost::EvOcGetWindow

TOcAppFrameHost

Syntax

virtual HWND EvOcGetWindow() const = 0;

Description

The HWND for the main window.


TOcAppFrameHost::ReleaseOcObject

TOcAppFrameHost

Syntax

virtual void ReleaseOcObject();

Description

Releases the TOcAppFrameHost object.


TOcAppFrameHost::OcApp

TOcAppFrameHost

Syntax

TOcApp* OcApp;

Description

The application’s TOcApp object.


TOcAppFrameHostMsg class

TOcAppFrameHost

Header File

ocf/ocapp.h

Base Class

TOcAppFrameHost

Description

An implementation of the TOcAppFrameHost class that handles ObjectComponents events by sending them to the application’s main window. Use a TOcAppFrameHostMsg object instead of TOcAppFrameHost object if you want to handle the ObjectComponents events in the main window procedure instead of in virtual functions.

Public Constructor and Destructor

TOcAppFrameHostMsg

Public Member Functions

EvOcAppBorderSpaceReq

EvOcAppBorderSpaceSet

EvOcAppDialogHelp

EvOcAppFrameRect

EvOcAppGetAccel

EvOcAppInsMenus

EvOcAppMenus

EvOcAppProcessMsg

EvOcAppRestoreUI

EvOcAppShutdown

EvOcAppStatusText

EvOcGetWindow

ReleaseOcObject

Protected Member Functions

ForwardEvent

ForwardEvent


TOcAppFrameHostMsg::TOcAppFrameHostMsg

TOcAppFrameHostMsg

Syntax

Constructor

TOcAppFrameHostMsg(TOcApp* ocApp)

Description

Creates a TOcAppFrameHostMsg object and attaches it to the application’s TOcApp object. (Create the TOcApp object first using the TOcAppHost class.)


TOcAppFrameHostMsg::EvOcAppBorderSpaceReq

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppBorderSpaceReq(TRect far* rect) ;

Description

Responds to an OC_APPBORDERSPACEREQ message sent to a container. The response is whether or not the container can give border space in its frame window to the server. By default, the OC_APPBORDERSPACEREQ message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppBorderSpaceSet

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppBorderSpaceSet(TRect far* rect) ;

Description

Responds to an OC_APPBORDERSPACESET message by making room in the container's frame window for the border space that the server has requested. By default, the OC_APPBORDERSPACESET message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppDialogHelp

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppDialogHelp(TOcDialogHelp far& dh) ;

Description

Responds to an OC_APPDIALOGHELP message. The dh parameter refers to one of the TOcDialogHelp enum constants that indicate the kind of dialog box the user has open. For example, dhBrowseLinks indicates that the Links dialog box is open. The TOcDialogHelp enum lists the help constants and their dialog box equivalents. By default, the OC_APPDIALOGHELP message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppFrameRect

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppFrameRect(TRect far* rect) = 0;

Description

Responds to an OC_APPFRAMERECT message sent to a container. The response is to get the coordinates of the client area rectangle of the application's main window. By default, the OC_APPFRAMERECT message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppGetAccel

See also

Syntax

virtual bool EvOcAppGetAccel(TOcGetAccel far* acc) = 0;

Description

Sends an OC_APPGETACCEL message to the application’s main window, forwarding the accelerator in acc.


TOcAppFrameHostMsg::EvOcAppInsMenus

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppInsMenus(TOcMenuDescr far& sharedMenu;

Description

Responds to an OC_APPINSMENUS message by merging the container's menu into the shared menu. The sharedMenu parameter refers to this merged menu. By default, the OC_APPINSMENUS message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppMenus

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppMenus(TOcMenuDescr far& md) = 0;

Description

Responds to an OC_OCAPPMENUS sent to the container. The response is to install a merged menu bar. By default, the OC_APPMENUS message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppProcessMsg

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppProcessMsg(MSG far* msg) = 0;

Description

Responds to an OC_APPROCESSMSG message sent to the container asking the server to process accelerators and other messages from the container's message queue. By default, the OC_APPROCESSMSG message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppRestoreUI

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppRestoreUI() = 0;

Description

Responds to an OC_APPRESTOREUI message by restoring the container's normal menu and borders because in-place editing has finished. By default, the OC_APPRESTOREUI message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppShutdown

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppShutdown() = 0;

Description

Responds to an OC_APPSHUTDOWN message indicating that the last embedded object has been closed. The response is to shut down the server. By default, the OC_APPSHUTDOWN message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcAppStatusText

TOcAppFrameHostMsg

Syntax

virtual bool EvOcAppStatusText(const char far* rect) = 0;

Description

Responds to an OC_APPSTATUSTEXT message by displaying text from the server on this container's status bar. By default, the OC_APPSTATUSTEXT message is sent to the application’s main window.


TOcAppFrameHostMsg::EvOcGetWindow

TOcAppFrameHostMsg

Syntax

virtual HWND EvOcGetWindow() const = 0;

Description

The HWND for the main window.


TOcAppFrameHostMsg::ReleaseOcObject

TOcAppFrameHostMsg

Syntax

virtual void ReleaseOcObject();

Description

Releases the TOcAppFrameHostMsg object.


TOcAppFrameHostMsg::ForwardEvent

TOcAppFrameHostMsg

Syntax 1

uint32 ForwardEvent(int eventID, const void far* param);

Description

Forwards an event and its parameters to the application’s main window.

Syntax 2

uint32 ForwardEvent(int eventId, uint32 param = 0);

Description

Forwards an event and its uint32 parameter to the application’s main window.


OC_APPxxxx Messages

See also	Linking and Embedding Messages

Header File

ocf/ocapp.h

Description

These messages are sent from ObjectComponents to the application's main window. They notify the application of signals and events that come from the OLE system. The actual message sent is WM_OCEVENT. The constants in the table below are carried in the message's wParam and identify particular events. To find out what each message carries in its lParam, see Event Handlers to look up the corresponding event handlers (such as EvOcAppBorderSpaceSet and EvOcAppMenus) in the ObjectWindows Help (OWL.HLP).

Applications that use the ObjectWindows Library can set up event handlers in their response tables using the EV_OC_xxxx macros defined in ocfevent.h. For more information about the data each message carries, see the descriptions of the corresponding event handlers.

The constants beginning OC_APP indicate events typically handled in the main frame window. Another set of constants beginning OC_VIEW indicate events typically handled in the view object.

Messages	Meaning

OC_APPDIALOGHELP	The user pressed the Help button in one of the standard OLE dialog boxes.

OC_APPBORDERSPACEREQ	Asks the container whether it can give the server border space in its frame window.

OC_APPBORDERSPACESET	Asks the container to give the server border space in its frame window.

OC_APPFRAMERECT	Requests coordinates for the inner rectangle of the container's main window.

OC_APPGETACCEL	Requests accelerators for menu merging purposes.

OC_APPINSMENUS	Asks the container to merge its menu into the shared menu bar.

OC_APPMENUS	Asks the container to install the merged menu bar.

OC_APPPROCESSMSG	Asks the container to process accelerators and other messages from the server's message queue.

OC_APPRESTOREUI	Tells the container to restore its normal menu and borders because in-place editing has ended.

OC_APPSHUTDOWN	Tells the server when its last linked or embedded object closes down. If the user did not launch the server directly, the server can terminate.

OC_APPSTATUSTEXT	Passes text for the status bar from the server to the container during in-place editing.


TOcModule typedef

TOcAppHost

Header File

ocf/ocapp.h

Syntax

typedef TOcAppHost TOcModule;

Description

A TOcModule object is a TOcAppHost object.


WM_OCEVENT Message

See also	Linking and Embedding Messages

Header File

ocf/ocapp.h

Description

ObjectComponents defines the WM_OCEVENT message in order to notify an application's window when significant OLE-related events occur.

Message	Meaning

WM_OCEVENT	Notification of an OLE event from ObjectComponents. The wParam value identifies the particular event.


TOcControl class

See also	Linking and Embedding Classes

Header File

ocf/occtrl.h

Base Class

TOcPart

Description

Represents a container’s view of an embedded OCX control.

You can use the TOcControl object to get or set the position, name, and status of an embedded OCX control.

Public Constructor and Destructor

TOcControl

~TOcControl

Public Member Functions

GetActiveControlView

GetEventTypeInfo

GetHeight

GetLeft

GetTop

GetUserName

GetWidth

InitObj

IsCancel

IsDefault

SetCancel

SetDefault

SetHeight

SetLeft

SetTop

SetUserName

SetWidth

Protected Data Members

pUserName

pEvents


TOcControl::TOcControl

See also	TOcControl

Constructor Syntax 1

TOcControl(TOcDocument& document, int id = 0, TOcControlEvent* pEv = NULL);

Description

Creates a TOcControl object with the identification (id) number that you specify. (Each control must have a unique identification number. If you specify an identification number of zero, a new identification number is created automatically.)

Initializes the pEvents data member to pEv and the pUserName data member to a unique name. The unique name is generated automatically.

Uses document to construct the TOcPart object upon which the TOcControl object is based.

Constructor Syntax 2

TOcControl(TOcDocument& document, const char far* name);

Description

Creates a TOcControl object from a storage (name) in the document you specify. Initializes the pUserName data member to zero.

Destructor Syntax

~TOcControl();

Description

Destroys the TOcControl object. Deletes the pUserName data member.

Remarks

After you create a TOcControl object, its InitObj function is called.


TOcControl::GetActiveControlView

TOcControl

Syntax

TOcView* GetActiveControlView();

Description

Returns the active TOcView object.


TOcControl::GetEventTypeInfo

TOcControl

Syntax

ITypeInfo* GetEventTypeInfo();

Description

Returns event type information for the control.


TOcControl::GetHeight

See also 	TOcControl

Syntax

long GetHeight();

Description

Returns the height of the control.


TOcControl::GetLeft

See also 	TOcControl

Syntax

long GetLeft();

Description

Returns the x-coordinate of the left edge of the control.


TOcControl::GetTop

See also 	TOcControl

Syntax

long GetTop();

Description

Returns the y-coordinate of the top edge of the control.


TOcControl::GetUserName

See also 	TOcControl

Syntax

TString& GetUserName();

Description

Returns the string stored in the pUserName data member.


TOcControl::GetWidth

See also 	TOcControl

Syntax

long GetWidth();

Description

Returns the width of the control.


TOcControl::InitObj

See also 	TOcControl

Syntax

virtual bool InitObj(TOcInitInfo far* initInfo);

Description

Initializes the TOcControl object:

Calls the TOcPart::InitObj function.

Creates a TOcControlEvent object (if one doesn’t exist already) and assigns it to the pEv data member.

Sets the initInfo.Storage object equal to the TOcPart::Storage data member.

Creates and initializes an OLE control using internal functions. (For more information, see the occtrl.cpp source file.)


TOcControl::IsCancel

See also 	TOcControl

Syntax

bool IsCancel() const;

Description

Returns true if the OcxCancel flag of the TOcPart::Flags data member is set. Returns false otherwise.


TOcControl::IsDefault

See also 	TOcControl

Syntax

bool IsDefault() const;

Description

Returns true if the OcxDefault flag of the TOcPart::Flags data member is set. Returns false otherwise.


TOcControl::SetCancel

See also 	TOcControl

Syntax

void SetCancel(bool cancel);

Description

Turns the OcxCancel setting of the TOcPart::Flags data member on or off according to the value in cancel.


TOcControl::SetDefault

See also 	TOcControl

Syntax

void SetDefault(bool def);

Description

Turns the OcxDefault setting of the TOcPart::Flags data member on or off according to the value in cancel.


TOcControl::SetHeight

See also 	TOcControl

Syntax

void SetHeight(long Value);

Description

Sets the height of the control to Value.


TOcControl::SetLeft

See also 	TOcControl

Syntax

void SetLeft(long Value);

Description

Sets the x-coordinate of the left edge of the control to Value.


TOcControl::SetTop

See also 	TOcControl

Syntax

SetTop(long Value);

Description

Sets the y-coordinate of the top edge of the control to Value.


TOcControl::SetUserName

See also

Syntax

void SetUserName(TString& name);

Description

Sets the pUserName data member equal to name.


TOcControl::SetWidth

See also 	TOcControl

Syntax

long SetWidth(long Value);

Description

Sets the width of the control to Value.


TOcControl::pUserName

See also 	TOcControl

Syntax

TString *pUserName;

Description

A pointer to the name of the control.

Each control in a container must have a unique name. When a control that is created with an identification number (using constructor Syntax 1), the pUserName data member is automatically assigned a unique name that is generated by the TOcPart::GetName function.


TOcControl::pEvents

See also 	TOcControl

Syntax

TOcControlEvent *pEvents;

Description

A pointer to the TOcControlEvent object for the control. (Each control has a TOcControlEvent object, which is specified in the TOcControl constructor.)


TOcControlEvent class

See also	Linking and Embedding Classes

Header File

ocf/occtrl.h

Description

Sends mouse and keyboard messages from a control to its container. Each TOcControlEvent object has a corresponding TOcControl object. (You must pass a TOcControlEvent object to the TOcControl constructor.)

You can handle additional events and send custom messages to the container by implementing a CustomEvent member function in a derived class.

Public Constructor and Destructor

TOcControlEvent

~TOcControlEvent

Public Member Functions

Click

CustomEvent

DblClick

ErrorEvent

ForwardClickEvent

ForwardKeyEvent

ForwardMouseEvent

GetControl

KeyDown

KeyUp

MouseDown

MouseMove

MouseUp

Public Data Members

pCtrl


TOcControlEvent::TOcControlEvent

See also	TOcControlEvent

Syntax

TOcControlEvent();

Description

Creates a TOcControlEvent object. Initializes the pCtrl data member to zero.

Destructor

~TOcControlEvent();

Description

Destroys the TOcControlEvent object.


TOcControlEvent::Click

See also 	TOcControlEvent

Syntax

long Click();

Description

Sends an OC_CTRLEVENT_CLICK message to the container’s window when the mouse is clicked on the control.


TOcControlEvent::CustomEvent

See also 	TOcControlEvent

Syntax

HRESULT CustomEvent(long *args);

Description

Sends an OC_CTRLEVENT_CUSTOMEVENT message to the container’s window when a non-keyboard, non-mouse event occurs. (The keyboard and mouse events are handled in the pre-defined event handlers, such as TOcControlEvent::DblClick.)

You can send a more specific message to the container’s window by implementing your own CustomEvent member function in a derived class. In your implementation, you can handle any standard windows event that occurs on the control, sending a custom message to the container’s window that defines the event. To send a custom message, use the ForwardEvent function of the associated TOcView object. (You can access the TOcView object by calling the TOcControl::GetActiveView function.)


TOcControlEvent::DblClick

See also 	TOcControlEvent

Syntax

long DblClick();

Description

Sends an OC_CTRLEVENT_DBLCLICK message to the container’s window when the mouse is double-clicked on the control.


TOcControlEvent::ErrorEvent

See also 	TOcControlEvent

Syntax

long ErrorEvent(short number TAutoString Description, SCODE SCode, TAutoString Source, TAutoString HelpFile, long helpContext, bool far* CancelDisplay);

Description

Sends an OC_CTRLEVENT_ERROREVENT message to the container’s window when an error occurs on the control.


TOcControlEvent::ForwardClickEvent

See also 	TOcControlEvent

Syntax

long ForwardClickEvent(long Msg);

Description

Sends a mouse-click message to the container’s window. Used in the mouse-click event handlers.


TOcControlEvent::ForwardKeyEvent

See also 	TOcControlEvent

Syntax

long ForwardKeyEvent(long Msg, short *KeyCode, short Shift);

Description

Sends a keyboard message to the container’s window. Used in keyboard event handlers.


TOcControlEvent::ForwardMouseEvent

See also 	TOcControlEvent

Syntax

long ForwardMouseEvent(long Msg, short *KeyCode, short Shift);

Description

Sends a general mouse message to the container’s window. Used in general mouse-event handlers. (General mouse-events include mouse-move events, but not mouse-click events.)


TOcControlEvent::GetControl

See also 	TOcControlEvent

Syntax

TOcControl* GetControl();

Description

Returns a pointer to the TOcControl object to which the TOcControlEvent object belongs. (The TOcControl object is stored in the pCtrl data member.


TOcControlEvent::KeyDown

See also 	TOcControlEvent

Syntax

long KeyDown(short far* KeyCode, short Shift);

Description

Sends an OC_CTRLEVENT_KEYDOWN message to the container’s window when a key is pressed.


TOcControlEvent::KeyUp

See also 	TOcControlEvent

Syntax

long KeyUp(short far* KeyCode, short Shift);

Description

Sends an OC_CTRLEVENT_KEYUP message to the container’s window when a key is released.


TOcControlEvent::MouseDown

See also 	TOcControlEvent

Syntax

long MouseDown(short Button, short Shift, long X, long Y);

Description

Sends an OC_CTRLEVENT_MOUSEDOWN message to the container’s window when the mouse button is held down.


TOcControlEvent::MouseMove

See also 	TOcControlEvent

Syntax

long MouseMove(short Button, short Shift, long X, long Y);

Description

Sends an OC_CTRLEVENT_MOUSEMOVE message to the container’s window when the mouse moves.


TOcControlEvent::MouseUp

See also 	TOcControlEvent

Syntax

long MouseUp(short Button, short Shift, long X, long Y);

Description

Sends an OC_CTRLEVENT_MOUSEUP message to the container’s window when the mouse button is released.


TOcControlEvent::pCtrl

See also 	TOcControlEvent

Syntax

TOcControl *pCtrl;

Description

A pointer to the TOcControl object to which the TOcControlEvent object belongs. (You link the TOcControl and TOcControlEvent objects in the TOcControl constructor.)


TOcxView class

See also	Linking and Embedding Classes

Header File

ocf/occtrl.h

Base Class

TOcView

Description

Represents an OCX container. Notifies embedded OCX controls when standard properties change. Provides standard property values upon request.

Public Constructor and Destructor

TOcxView

~TOcxView

Public Member Functions

SetBackColor

SetDisplayAsDefault

SetDisplayName

SetFont

SetForeColor

SetLocaleID

SetMessageReflect

SetScaleUnits

SetShowGrabHandles

SetShowHatching

SetSupportsMnemonics

SetTextAlign

SetUIDead

SetUserMode

Protected Member Functions

GetAmbientValue

GetBackColor

GetDisplayAsDefault

GetDisplayName

GetForeColor

GetLocaleID

GetMessageReflect

GetScaleUnits

GetShowGrabHandles

GetShowHatching

GetSupportsMnemonics

GetTextAlign

GetUIDead

GetUserMode

SetAmbBackColor

SetAmbDisplayAsDefault

SetAmbDisplayName

SetAmbFont

SetAmbForeColor

SetAmbLocaleID

SetAmbMessageReflect

SetAmbScaleUnits

SetAmbShowGrabHandles

SetAmbShowHatching

SetAmbSupportsMnemonics

SetAmbTextAlign

SetAmbUIDead

SetAmbUserMode

Public Data Members

pBlankString


TOcxView::TOcxView

See also	TOcxView

Constructor

TOcxView(TOcDocument& doc, TRegList* regList = 0, IUnknown* outer = 0);

Description

Creates a TOcxView object, which is based on a TOcView object. (Calls the TOcView constructor using the values of the doc, regList, and outer parameters. For more information about these parameters, see the TOcView::TOcView topic.) Initializes the pBlankString data member to a space character.

Destructor

~TOcxView();

Description

Releases the TOcxView object. Deletes the pBlankString data member.


TOcxView::SetBackColor

See also 	TOcxView

Syntax

void SetBackColor(long);

Description

Notifies every control that the container’s background color has changed.


TOcxView::SetDisplayAsDefault

See also 	TOcxView

Syntax

void SetDisplayAsDefault(bool);

Description

Notifies every control that the container’s default control has changed.


TOcxView::SetDisplayName

See also 	TOcxView

Syntax

void SetDisplayName(TString&);

Description

Notifies every control that the container’s display name has changed.


TOcxView::SetFont

See also 	TOcxView

Syntax

void SetFont(IDispatch);

Description

Notifies every control that the container’s font has changed.


TOcxView::SetForeColor

See also 	TOcxView

Syntax

void SetForeColor(long);

Description

Notifies every control that the container’s foreground color has changed.


TOcxView::SetLocaleID

See also 	TOcxView

Syntax

void SetLocaleID(long);

Description

Notifies every control that the container’s locale identification number has changed.


TOcxView::SetMessageReflect

See also 	TOcxView

Syntax

void SetMessageReflect(bool);

Description

Notifies every control that the container’s message-reflect property has changed.


TOcxView::SetScaleUnits

See also 	TOcxView

Syntax

void SetScaleUnits(TString&);

Description

Notifies every control that the container’s scale units have changed.


TOcxView::SetShowGrabHandles

See also 	TOcxView

Syntax

void SetShowGrabHandles(bool);

Description

Notifies every control that the container’s show-grab-handles property has changed.


TOcxView::SetShowHatching

See also 	TOcxView

Syntax

void SetShowHatching(bool);

Description

Notifies every control that the container’s show-hatching property has changed.


TOcxView::SetSupportsMnemonics

See also 	TOcxView

Syntax

void SetSupportsMnemonics(bool);

Description

Notifies every control that the container’s supports-mnemonics property has changed.


TOcxView::SetTextAlign

See also 	TOcxView

Syntax

void SetTextAlign(short);

Description

Notifies every control that the container’s text alignment has changed.


TOcxView::SetUIDead

See also 	TOcxView

Syntax

void SetUIDead(bool);

Description

Notifies every control that the container’s user-interface status has changed.


TOcxView::SetUserMode

See also 	TOcxView

Syntax

void SetUserMode(bool);

Description

Notifies every control that the container’s user mode has changed.


TOcxView::GetAmbientValue

See also 	TOcxView

Syntax

long GetAmbientValue(long AmbientMsg, long Default);

Description

Returns an ambient property value that the container provides in response to the AmbientMsg message. If the container’s window doesn’t respond with a value, the Default value is returned instead. The GetAmbientValue function is used by the other “Get” functions of the TOcxView class, such as GetUserMode.


TOcxView::GetBackColor

See also 	TOcxView

Syntax

long GetBackColor();

Description

Returns the background color of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETBACKCOLOR message.

If the container’s window doesn’t respond, the GetBackColor function returns RGB(0x80, 0x80, 0x80).


TOcxView::GetDisplayAsDefault

See also 	TOcxView

Syntax

bool GetDisplayAsDefault();

Description

Returns the display-as-default property of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETDISPLAYASDEFAULT message.

If the container’s window doesn’t respond, the GetDisplayAsDefault function returns false.


TOcxView::GetDisplayName

See also 	TOcxView

Syntax

TString& GetDisplayName();

Description

Returns the display name of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETDISPLAYNAME message.

If the container’s window doesn’t respond, the GetDisplayName function returns *pBlankString.


TOcxView::GetForeColor

See also 	TOcxView

Syntax

long GetForeColor();

Description

Returns the foreground color of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETFORECOLOR message.

If the container’s window doesn’t respond, the GetForeColor function returns RGB(0x00, 0x00, 0x00).


TOcxView::GetLocaleID

See also 	TOcxView

Syntax

long GetLocaleID();

Description

Returns the locale identification number of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETLOCALEID message.

If the container’s window doesn’t respond, the GetLocaleID function returns LOCALE_USER_DEFAULT.


TOcxView::GetMessageReflect

See also 	TOcxView

Syntax

bool GetMessageReflect();

Description

Returns the message-reflect property of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETMESSAGEREFLECT message.

If the container’s window doesn’t respond, the GetMessageReflect function returns false.


TOcxView::GetScaleUnits

See also 	TOcxView

Syntax

TString& GetScaleUnits();

Description

Returns the scale units of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETSCALEUNITS message.

If the container’s window doesn’t respond, the GetScaleUnits function returns *pBlankString.


TOcxView::GetShowGrabHandles

See also 	TOcxView

Syntax

bool GetShowGrabHandles();

Description

Returns the get-show-grab-handles property of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETSHOWGRABHANDLES message.

If the container’s window doesn’t respond, the GetShowGrabHandles function returns false.


TOcxView::GetShowHatching

See also 	TOcxView

Syntax

bool GetShowHatching();

Description

Returns the show-hatching property of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETSHOWHATCHING message.

If the container’s window doesn’t respond, the GetShowHatching function returns false.


TOcxView::GetSupportsMnemonics

See also 	TOcxView

Syntax

bool GetSupportsMnemonics();

Description

Returns the get-supports-mnemonics property of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETSUPPORTSMNEMONICS message.

If the container’s window doesn’t respond, the GetSupportsMnemonics function returns false.


TOcxView::GetTextAlign

See also 	TOcxView

Syntax

short GetTextAlign();

Description

Returns the text alignment property of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETTEXTALIGN message.

If the container’s window doesn’t respond, the GetTextAlign function returns 0.


TOcxView::GetUIDead

See also 	TOcxView

Syntax

bool GetUIDead();

Description

Returns the user interface status of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETUIDEAD message.

If the container’s window doesn’t respond, the GetUIDead function returns false.


TOcxView::GetUserMode

See also 	TOcxView

Syntax

bool GetUserMode();

Description

Returns the user mode of the container’s window, which the container’s window provides in response to the OC_AMBIENT_GETUSERMODE message.

If the container’s window doesn’t respond, the GetUserMode function returns true.


TOcxView::SetAmbBackColor

See also 	TOcxView

Syntax

void SetAmbBackColor(long Color);

Description

Sends an OC_AMBIENT_SETBACKCOLOR message to the container’s window, forwarding the value in Color.


TOcxView::SetAmbDisplayAsDefault

See also 	TOcxView

Syntax

void SetAmbDisplayAsDefault(bool Disp);

Description

Sends an OC_AMBIENT_SETDISPLAYASDEFAULT message to the container’s window, forwarding the value in Disp.


TOcxView::SetAmbDisplayName

See also 	TOcxView

Syntax

void SetAmbDisplayName(TString& Name);

Description

Sends an OC_AMBIENT_SETDISPLAYNAME message to the container’s window, forwarding the value in Name.


TOcxView::SetAmbFont

See also 	TOcxView

Syntax

void SetAmbFont(IDispatch *pFontDisp);

Description

Sends an OC_AMBIENT_SETFONT message to the container’s window, forwarding the value in pFontDisp.


TOcxView::SetAmbForeColor

See also 	TOcxView

Syntax

void SetAmbForeColor(long Color);

Description

Sends an OC_AMBIENT_SETFORECOLOR message to the container’s window, forwarding the value in Color.


TOcxView::SetAmbLocaleID

See also 	TOcxView

Syntax

void SetAmbLocaleID(long LocaleID);

Description

Sends an OC_AMBIENT_SETLOCALEID message to the container’s window, forwarding the value in LocaleID.


TOcxView::SetAmbMessageReflect

See also 	TOcxView

Syntax

void SetAmbMessageReflect(bool MsgRef);

Description

Sends an OC_AMBIENT_SETMESSAGEREFLECT message to the container’s window, forwarding the value in MsgRef.


TOcxView::SetAmbScaleUnits

See also 	TOcxView

Syntax

void SetAmbScaleUnits(TString &scaleUnits);

Description

Sends an OC_AMBIENT_SETSCALEUNITS message to the container’s window, forwarding the value in scaleUnits.


TOcxView::SetAmbShowGrabHandles

See also 	TOcxView

Syntax

void SetAmbShowGrabHandles(bool Handles);

Description

Sends an OC_AMBIENT_SETSHOWGRABHANDLES message to the container’s window, forwarding the value in Handles.


TOcxView::SetAmbShowHatching

See also 	TOcxView

Syntax

void SetAmbShowHatching(bool Hatch);

Description

Sends an OC_AMBIENT_SETSHOWHATCHING message to the container’s window, forwarding the value in Hatch.


TOcxView::SetAmbSupportsMnemonics

See also 	TOcxView

Syntax

void SetAmbSupportsMnemonics(bool Mnem);

Description

Sends an OC_AMBIENT_SUPPORTSMNEMONICS message to the container’s window, forwarding the value in Mnem.


TOcxView::SetAmbTextAlign

See also 	TOcxView

Syntax

bool SetAmbTextAlign(short Align);

Description

Sends an OC_AMBIENT_SETTEXTALIGN message to the container’s window, forwarding the value in Align.


TOcxView::SetAmbUIDead

See also 	TOcxView

Syntax

void SetAmbUIDead(bool Dead);

Description

Sends an OC_AMBIENT_SETBUIDEAD message to the container’s window, forwarding the value in Dead.


TOcxView::SetAmbUserMode

See also 	TOcxView

Syntax

void SetAmbUserMode(bool Mode);

Description

Sends an OC_AMBIENT_SETUSERMODE message to the container’s window, forwarding the value in Mode.


TOcxView::pBlankString

See also 	TOcxView

Syntax

TString *pBlankString;

Description

Stores a blank string. Used as a default value for some of the “Set” functions of the TOcxView class.


TCtrlEvent struct

Linking and embedding structs

Header File

ocf/occtrl.h

Description

The base structure for all OCX control event messages.

Public Data Members

Ctrl


TCtrlEvent::Ctrl

TCtrlEvent

Syntax

TOcControl* Ctrl;

Description

A pointer to the control referred to by the TCtrlEvent struct.


TCtrlMouseEvent struct

See also	Linking and embedding structs

Header File

ocf/occtrl.h

Base Structure

TCtrlEvent

Description

Structure for mouse events.

Public Data Members

Button

Shift

X

Y


TCtrlMouseEvent::Button

TCtrlMouseEvent

Syntax

short Button;

Description

The mouse button pressed.


TCtrlMouseEvent::Shift

TCtrlMouseEvent

Syntax

short Shift;

Description

A value indicating whether or not the Shift key was pressed down when the mouse event occurred.


TCtrlMouseEvent::X

TCtrlMouseEvent

Syntax

long X;

Description

The x-coordinate of the mouse pointer on the screen.


TCtrlMouseEvent::Y

TCtrlMouseEvent

Syntax

long Y;

Description

The y-coordinate of the mouse pointer on the screen.


TCtrlKeyEvent struct

See also	Linking and Embedding Structs

Header File

ocf/occtrl.h

Base Structure

TCtrlEvent

Description

Structure for keyboard events.

Public Data Members

KeyCode

Shift


TCtrlKeyEvent::KeyCode

TCtrlKeyEvent

Syntax

short KeyCode;

Description

The code for the pressed key.


TCtrlKeyEvent::Shift

TCtrlKeyEvent

Syntax

short Shift;

Description

A value indicating whether or not the Shift key was pressed down when the keyboard event occurred.


TCtrlFocusEvent struct

See also	Linking and Embedding Structs

Header File

ocf/occtrl.h

Base Structure

TCtrlEvent

Description

Structure for focus events.

Public Data Members

GotFocus


TCtrlFocusEvent::GotFocus

TCTrlFocusEvent

Syntax

bool GotFocus;

Description

A boolean value indicating whether or not the control has the focus.


TCtrlErrorEvent struct

See also	Linking and Embedding Structs

Header File

ocf/occtrl.h

Base Structure

TCtrlEvent

Description

Structure for error events.

Public Data Members

Number

Description

SCode

Source

HelpFile

HelpContext

CancelDisplay


TCtrlErrorEvent::Number

TCtrlErrorEvent

Syntax

short Number;

Description

An error number.


TCtrlErrorEvent::Description

TCtrlErrorEvent

Syntax

TAutoString Description;

Description

An error description.


TCtrlErrorEvent::SCode

TCtrlErrorEvent

Syntax

SCODE Scode;

Description

The error SCODE.


TCtrlErrorEvent::Source

TCtrlErrorEvent

Syntax

TAutoString Source;

Description

The name of the error source.


TCtrlErrorEvent::HelpFile

TCtrlErrorEvent

Syntax

TAutoString HelpFile;

Description

The name of the Help file associated with the control.


TCtrlErrorEvent::HelpContext

TCtrlErrorEvent

Syntax

long HelpContext;

Description

The Help context identification number associated with the control.


TCtrlErrorEvent::CancelDisplay

TCtrlErrorEvent

Syntax

bool CancelDisplay;

Description

A boolean value indicating whether or not to display a Cancel box.


TCtrlCustomEvent struct

See also	Linking and Embedding Structs

Header File

ocf/occtrl.h

Base Structure

TCtrlEvent

Description

Structure for custom events.

Public Data Members

Args


TCtrlCustomEvent::Args

TCtrlCustomEvent

Syntax

TAutoStack *Args;

Description

The arguments for the custom event.


TOcDataProvider class

See Also	Linking and Embedding Classes

Header File

ocdata.h

Description

Along with TOcLinkView, TOcDataProvider provides support for serving a portion of a document. With the functionality of TOcDataProvider, a container can embed or link to a selection in the server. TOcDataProvider creates a site for this data provider and connects the part and the site. A typical cut and copy transaction using TOcDataProvider is illustrated in the tutorial program, Step17dv.cpp, on your distribution disk.

A TOcDataProvider object is created whenever a selection is copied to the Clipboard. If a server supports linking to selection, a moniker (a name an application assigns to the item for linking purposes) is created for the selection. Therefore, in the constructor of TOcDataProvider, the Rename function is called.

Public Constructors and Destructors

TOcDataProvider

Public Member Functions

AddRef

Disconnect

GetUserData

QueryInterface

Release

Rename

SetUserData

Protected Members Functions

CountFormats

Draw

GetFormat

GetFormatData

GetPartSize

Save

Protected Data Members

Origin

Extent


See Also

TOcDocument

TOcView

TOcPart


TOcDataProvider::TOcDataProvider

See Also	TOcDataProvider

Syntax

TOcDataProvider(TOcView& ocView, TRegList* regList, IUnknown* outer = 0, void* userData, TDeleteUserData callBack = 0);

Description

Constructs a TOcDataProvider object associated with the given server view and creates a site for this remote view. view refers to the TOcView object associated with the data provider object. Calls Rename to create a moniker, a name an application assigns to the selection for linking purposes.

regList is the registration structure for a particular document. Use the BEGIN_REGISTRATION and END_REGISTRATION macros to create an object of type TRegList.

outer is the root interface of an outer object inside which the new linked view is asked to aggregate itself.

userData contains information the application passes in so that it can remember the selection that is copied. Because TOcDataProvider performs delayed rendering of the selection, the application is asked to render the selection at paste, rather than at copy time. However, the selection can change between the time it's copied and then pasted. Therefore, TOcDataProvider needs to remember the selection at the time the copying took place.

When it’s time to render or paint the selection, TOcDataProvider gives the userData back to the server application. It is the responsibility of the application to reestablish the selection through the use of userData.

callBack is a callback function of type TDeleteUserData. When the TOcDataProvider object is destroyed, it calls this callback function in the server application to give it a chance to clean up the userData it passes in.

The TDeleteUserData callback function is defined as

typedef void (*TDeleteUserData)(void* userData);


See Also

TOcDataProvider::Rename

Registration Macros (OWL.HLP)

TOcDocument

TOcView


TOcDataProvider::AddRef

See Also	TOcDataProvider

Syntax

ulong _IFUNC AddRef();

Description

Increases the reference count on the linked view object. Initializes the reference count to 1. If this is not aggregated, AddRef returns the TOcDataProvider object's reference count. The reference count indicates how many client applications hold pointers to this object.


See Also

TUnknown::GetRefCount


TOcDataProvider::Disconnect

TOcDataProvider

Syntax

void Disconnect();

Description

Called when the user wants the server to render its data right away. This happens when a cut operation takes place (because the selection no longer exists after the cut is performed) and when a server application shuts down while it has a selection copied on the Clipboard.


TOcDataProvider::GetUserData

See Also	TOcDataProvider

Syntax

void* GetUserData();

Description

Returns the user data, which is the information the application uses to remind itself of the attributes of the selection. It is important for TOcDataProvider to have this information because the selection might change between the time it is copied and pasted. When it's time to render or paint the selection, TOcDataProvider gives the userData back to the server application.


See Also

TOcDataProvider::SetUserData


TOcDataProvider::QueryInterface

See Also	TOcDataProvider

Syntax

HRESULT _IFUNC QueryInterface(const GUID far& iid, void far*far* iface);

Description

Asks for the interface identified by iid and returns the supported interface through iface. If the given interface is not supported, iface returns 0.


See Also

TOcLinkView::QueryInterface


TOcDataProvider::Release

TOcDataProvider

Syntax

ulong _IFUNC Release();

Description

 Deletes the object when the reference count reaches zero. Releases the TOcDataProvider object, which means that the clipboard becomes the owner of this object. The TOcDataProvider object is destroyed whenever the clipboard releases it when something else is copied to the clipboard.


TOcDataProvider::Rename

TOcDataProvider

Syntax

void Rename();

Description

Establishes the moniker for the server document and then sends an OC_VIEWGETITEMNAME message to TOleWindow. It is the server application’s responsibility to return the moniker for the selection or the whole document.


TOcDataProvider::SetUserData

See Also	TOcDataProvider

Syntax

void SetUserData(void* userData);

Description

Sets the userData, which is the information the application uses to remind itself of the attributes of the selection. It is important for TOcDataProvider to have this information because the selection might change between the time it is copied and pasted. When it's time to render or paint the selection, TOcDataProvider gives the userData back to the server application. It's the application's responsibility to reestablish the selection through the use of userData.


See Also

TOcDataProvider::GetUserData


TOcDataProvider::CountFormats

TOcDataProvider

Syntax

UINT _IFUNC CountFormats();

Description

CountFormats returns the number of Clipboard formats the server application supports.


TOcDataProvider::Draw

See Also	TOcDataProvider

Syntax

HRESULT _IFUNC Draw(HDC dc, const RECTL far* pos, const RECTL far* clip, TOcAspect aspect, TOcDraw bd);

Description

Paints the metafile, sets up the window origin and extent with the proper values, and sends an OC_VIEWPAINT message to TOleWindow to actually paint the selection into the metafile DC. TOleWindow uses two data members of the TOcViewPaint structure to determine how to paint the metafile: PaintSelection and Moniker. PaintSelection is true, only the selection is painted. If Moniker is not null, the link view corresponding to this Moniker is painted.


See Also

TOleWindowOWL.HLP)


TOcDataProvider::GetFormat

See Also	TOcDataProvider

Syntax

HRESULT _IFUNC GetFormat(uint index, TOcFormatInfo far* fmt);

Description

Returns the data format identified by index. This function is primarily used internally to return the supported Clipboard formats from the registration table.


See Also

TOcDataProvider::GetFormatData


TOcDataProvider::GetFormatData

See Also	TOcDataProvider

Syntax

HANDLE _IFUNC GetFormatData(TOcFormatInfo far* fmt);

Description

When the user does a paste into the container, this function is called to render native data formats in a memory handle. (The server application needs to render the selection into a handle.) GetFormatData also sends an OC_VIEWCLIPDATA message to TOleWindow.


See Also

TOcDataProvider::Save

TOcDataProvider::GetFormat

TOleWindowOWL.HLP)


TOcDataProvider::GetPartSize

TOcDataProvider

Syntax

HRESULT _IFUNC GetPartSize(TSize far* size);

Description

Returns the size of the server document. When a paste operation occurs in a container, the server is asked to render its data through TOcDataProvider object on the Clipboard. To do this, the container calls GetPartSize to get the size of the server document selection. Once the container has the size of the document selection, the TOcDataProvider draws the served selection of the document.


TOcDataProvider::Save

See Also	TOcDataProvider

Syntax

HRESULT _IFUNC Save(IStorage*, BOOL sameAsLoad, BOOL remember);

Description

For an embedded source, Save renders the selection in IStorage. When the user pastes data into the container, TOcDataProvider renders the data format in the storage media selected by the user.

The server renders its native data in a handle. To save a selection to the IStorage passed in to TOcDataProvider, the server needs to send a message: OC_VIEWSAVEPART to TOleView. (TOleView::EvOcViewSavePart is the handler for this message.) TOcSaveLoad lets TOleView know whether a selection or whole document needs to be saved.

For native data, GetFormatData is called.


See Also

TOcDataProvider::GetFormatData

TOleViewOWL.HLP)


TOcDataProvider::Extent

TOcDataProvider

Syntax

TSize Extent;

Description

The size of the document containing the selection.


TOcDataProvider::Origin

TOcDataProvider

Syntax

TPoint Origin;

Description

The coordinates of the top left corner of the view relative to the document.


TOcDocument class

See also	Linking and Embedding Classes

Header File

ocf/ocdoc.h

Description

The primary responsibility of a TOcDocument is to save and load data in a compound file using hierarchically ordered storages. (A storage is a compartment within a file, just as a directory is a compartment on a disk.) By default the application's native data always goes in the document's root storage, but the application is free to create its own storages in the same file. TOcDocument creates new storages below the root as necessary for OLE objects that the user inserts into the compound document. The new storages take their names from the names of the objects they store. TOcView automatically assigns a unique string identifier to each new object.

Both servers and containers can create objects of type TOcDocument. In the container, this object represents an entire compound document. In the server, it represents the data for a single OLE object. (The server's single OLE object can have other OLE objects linked or embedded in it.)

A TOcDocument object manages the collection of TOcPart objects that are deposited in one of the container's documents. It does not draw the data on the screen. To do that, every TOcDocument needs a corresponding TOcView or TOcRemView object. An application can possess multiple pairs of associated document and view objects, one for each open document.

A container creates a TOcView object to draw its compound document in the container's own window. Because the window where the server draws belongs to the container (it is a child of the container's window), the server must create a remote view object (TOcRemView) for each document.

In spite of the similar names, TOcDocument and TOcView are not part of the ObjectWindows Doc/View model. The nature of OLE makes it useful to separate data from its graphical representation, and the terms document and view express that separation even outside of ObjectWindows.

To execute its tasks, a TOcDocument must use the standard OLE interfaces IStorage and IStream. Usually it is not necessary to use these interfaces directly because ObjectComponents implements them for you in its TOcStorage and TOcStream classes. These classes are thin wrappers around standard OLE interfaces. The implementation of TOcDocument makes use of both objects.

Public Constructors and Destructor

TOcDocument

~TOcDocument

Public Member Functions

Close

GetActiveView

GetLinks

GetName

GetOcApp

GetParts

GetStorage

GetViews

LoadParts

RenameParts

RestoreStorage

SaveParts

SaveToFile

SetActiveView

SetName

SetStorage

SetStorage


TOcDocument::TOcDocument

See also	TOcDocument

Constructor Syntax 1

TOcDocument(TOcApp& app, const char far* fileName = 0);

Description

Creates a new document object for the application and optionally assigns a file name for storing the document. A container uses this constructor for each document the user opens.

Constructor Syntax 2

TOcDocument(TOcApp& app, const char far* fileName, IStorage far* storageI);

Description

Creates a new document object for the application and assigns a particular file and storage object to hold the document. The container calls this constructor when opening an existing file. The server and the container each create their own TOcDocument object for the object they share, but both their objects point to the same file for storing the object.

IStorage is the standard OLE storage interface. ObjectComponents implements this interface in the TOcStorage class. It is usually not necessary to manipulate the IStorage interface or the TOcStorage class directly in an ObjectComponents application.

Destructor Syntax

~TOcDocument();

Description

Destroys the document object.


TOcDocument::Close

See also	TOcDocument

Syntax

void Close();

Description

A container calls TOcPart::Close for each object in the compound document to release its servers. TOleDocument calls this function automatically when asked to close down.


TOcDocument::GetActiveView

See also	TOcDocument

Syntax

TOcView* GetActiveView();

Description

Returns a pointer to the active view. TOcPart calls this method to coordinate changing focus among active parts.


TOcDocument::GetLinks

Syntax

TOcLinkCollection& GetLinks();

Description

Returns the collection of associated links.


TOcDocument::GetName

See also	TOcDocument

Syntax

string GetName() const;

Description

Returns the name of the file where the document will be stored. ObjectComponents keeps track of the name in order to create links correctly.


TOcDocument::GetOcApp

Syntax

TOcApp& GetOcApp();

Description

Returns the associated application object.


TOcDocument::GetParts

See also	TOcDocument

Syntax

TOcPartCollection& GetParts();

Description

Returns an object with information about all the parts in the document. Each part corresponds to a linked or embedded object. Create an iterator of type TOcPartCollectionIter to loop through the collection and extract information about individual parts.


TOcDocument::GetStorage

See also	TOcDocument

Syntax

TOcStorage* GetStorage();

Description

Returns the document file's root storage.


TOcDocument::GetViews

Syntax

TOcLinkCollection& GetViews();

Description

Returns the collection of associated views.


TOcDocument::LoadParts

See also	TOcDocument

Syntax

bool LoadParts();

Description

Reads all the linked and embedded parts saved in a compound file. LoadParts does not necessarily load all the data from all the parts into memory immediately. The data is needed only if the object is visible.

LoadParts returns true if all the parts are read successfully. If no file has yet been assigned to the document, then there is nothing to load and the function still returns true. (A document can acquire a file from its constructor, from SaveToFile, or from SetStorage.)


TOcDocument::RenameParts

See also	TOcDocument

Syntax

void RenameParts(IBRootLinkable far* BLDocumentI);

Description

Call this whenever the name of the document file changes. RenameParts updates the internal name stored with each part so that other applications can still link to them correctly.

IBRootLinkable is a custom OLE interface defined in the BOCOLE support library. Objects of type TOcView implement this interface, so it is usually not necessary to implement it yourself. Simply pass the document's view object to RenameParts.

TOcView calls this function automatically if the view is renamed.


TOcDocument::RestoreStorage

TOcDocument

Syntax

bool RestoreStorage();

Description

Sets the storage to its original path.


TOcDocument::SaveParts

See also	TOcDocument

Syntax

bool SaveParts(IStorage* storage = 0, bool sameAsLoaded = true, remember = true);

Description

Writes all the document's linked and embedded objects to the document's file. storage is the root storage in the file. A container's TOcDocument creates the storage object when the document is created or the first time it is saved. Find the object by calling GetStorage. A server gets the storage object from the container. It is usually not necessary to manipulate the storage object directly.

sameAsLoaded should be true unless the name of the document file has changed since the last time the document was loaded or saved.

SaveParts returns true if all the objects are successfully written to the file.

LoadParts and SaveParts are called by the Open and Commit methods in TOleDocument.


TOcDocument::SaveToFile

See also	TOcDocument

Syntax

bool SaveToFile(const char far* newName);

Description

Saves the document in the file named by newName. Usually a container calls this function when the user chooses File|Save for an unnamed document or File|Save As for any document. SaveToFile creates a new storage object and then calls SaveParts. It returns true if all the linked and embedded parts are successfully saved.


TOcDocument::SetActiveView

TOcDocument

Syntax

void SetActiveView(TOcView* view);

Description

A TOcView object calls this method when it is activated so that the document can locate the active view. TOcDocument communicates only with the active view. The active view sends messages to the corresponding window, perhaps a TOleView window. This window is responsible for telling other windows about changes.


See Also

TOcDocument::GetActiveView


TOcDocument::SetName

TOcDocument

Syntax

void SetName(const string& newName);

Description

Tells the document the name of the file where it will be stored. ObjectComponents needs to know the name in order to create links correctly. More specifically, SetName causes ObjectComponents to update the OLE moniker that a link server must provide.


See Also

TOcDocument::GetName


TOcDocument::SetStorage

TOcDocument

Syntax

Form 1

void SetStorage(const char far* path);

Form 2

void SetStorage(IStorage* storage);

Description

Assigns the document a storage for writing its data. storage becomes the document's root storage. Each linked or embedded object gets its own substorage under the root storage.

Form 1: Creates a compound file using the name in path and assigns the root storage of the new file to be the root storage of the document. Usually a container calls this function when the user chooses File|Save for an unnamed document or File|Save As for any document.

Form 2: Assigns storage to be the document's root storage. Usually a server calls this function when the container passes it an IStorage object. (An IStorage object implements the standard OLE interface IStorage. Usually it is not necessary to manipulate this object directly.)


ee Also

TOcDocument::GetStorage


TOcLinkView class

See also	Linking and Embedding Classes

Header File

oclink.h

Description

Derived from TUnknown, TOcLinkView provides linking support for a portion of or an entire document. TOcLinkView is a connector object located between the server application and the container that helps containers establish links to the server document. TOcLinkView is similar to TOcRemView in that they both comminicate with the container through OLE interfaces. Application specific operators, such as saving the selection and painting the selection, are deligated to an OWL OLE class TOLeLinkView.

The main purpose of a class derived from TOcLinkView is to attach a view to a portion of a document whenever a link is created to a selection within a server document. After this link is established, the container receives change notification messages via the following sequence of steps:

1.	When TOleLinkView receives a notification message, it checks to see if the selection it represents has changed. If the selection has changed, TOleLinkView notifies TOcLinkView about the change by calling TOcLinkView::Invalidate() method.

2.	When TOcLinkView TOcLinkView::Invalidate in turn notifies the container through OLE interfaces that the selection has changed..

Public Constructor

TOcLinkView

Public Member Functions

AddRef

Detach

Disconnect

GetLinkRect

GetMoniker

Invalidate

QueryInterface

Release

SetMoniker

Protected Member Functions

Close

CountFormats

DoQueryInterface

Draw

GetFormat

GetFormatData

GetPartSize

Open

QueryObject

SetPartPos

SetPartSize


TOcLinkView::TOcLinkView

See also	TOcLinkView

Syntax

TOcLinkView(TOcView* ocView, TRegList* regList = 0, IUnknown* outer = 0);

Description

Constructs a TOcLinkView object and creates a site for this remote view. view refers to the TOcView object that corresponds to the link view. TOcView manages the appearance of the document on the screen, and TOcLinkView manages the appearance of the linked view.

regList is the registration structure for a particular document. Use the BEGIN_REGISTRATION and END_REGISTRATION macros to create an object of type TRegList.

outer is the root interface of an outer object inside which the new linked view is asked to aggregate itself.


TOcLinkView::AddRef

See also	TOcLinkView

Syntax

ulong _IFUNC AddRef();

Description

 Increases the reference count on the linked view object. Initializes the reference count to 1. If this is not aggregated, then returns the TLinkView object's reference count. The reference count indicates how many client applications hold pointers to this object, and have linked views to this object.


TOcLinkView::Detach

See also	TOcLinkView

Syntax

int Detach();

Description

Detaches the link view from its document and releases the site. Call Detach before cutting and pasting a document to the Clipboard.


TOcLinkView::Disconnect

TOcLinkView

Syntax

void Disconnect();

Description

Disconnects this link view from the client application's site (the area the container has alloted for displaying the linked object).


TOcLinkView::GetLinkRect

See also	TOcLinkView

Syntax

void GetLinkRect();

Description

Gets the initial size and position of the link view from the application. This is the actual area where the container application can draw the linked object.


TOcLinkView::GetMoniker

See also	TOcLinkView

Syntax

TString& GetMoniker();

Description

Returns the moniker (the source file's path name and the object hierarchy) for the selection in a container document associated with this TOcLinkView server's view.

By looking at the moniker, the application can find the corresponding objects in its document. A moniker functions much like a map in that it shows where the linked object's data is stored and explains how to find the data. For example, the moniker returned from a word processor for a selected range of text could be the start and end offset of a text stream. The moniker returned for a spreadsheet range could be something like A1:D6. Anything that a server application can use to map to its data can be used as a moniker.


TOcLinkView::Invalidate

See also	TOcLinkView

Syntax

void Invalidate(TOcInvalidate);

Description

Invalidates the container's site corresponding to this remote view. Notifies the container's active view that the server has changed either the appearance or the content of the active linked view.


TOcLinkView::QueryInterface

See also	TOcLinkView

Syntax

HRESULT _IFUNC QueryInterface(const GUID far& iid, void far*far* iface)

Description

Asks whether the link view object supports the interface identified by iid. If the object supports the interface, QueryInterface returns HR_NOERROR and places a pointer to the interface in pif.


TOcLinkView::Release

TOcLinkView

Syntax

ulong _IFUNC Release();

Description

Releases the server's link views. Deletes the object when the reference count reaches zero.


TOcLinkView::SetMoniker

See also	TOcLinkView

Syntax

void SetMoniker(const char far* name);

Description

Establishes the moniker for this server document's link viewer object.


TOcLinkView::Close

TOcLinkView

Syntax

HRESULT _IFUNC Close();

Description

Disconnects the linked view from from its container.


TOcLinkView::CountFormats

TOcLinkView

Syntax

uint _IFUNC CountFormats();

Description

Returns the number of Clipboard formats the server supports.


TOcLinkView::DoQueryInterface

See also	TOcLinkView

Syntax

HRESULT _IFUNC DoQueryInterface(const IID farpif);

Description

Call DoQueryInterface  on the linked view to do a QueryInterface on the actual server that the view supports. This function gives sites the ability to ask for server interfaces.


TOcLinkView::Draw

See also	TOcLinkView

Syntax

HRESULT _IFUNC Draw(HDC, const RECTL far*, const RECTL far*, TOcAspect, TOcDraw bd);

Description

Draws the linked server objects on the screen.


TOcLinkView::GetFormat

See also	TOcLinkView

Syntax

HRESULT _IFUNC GetFormat(uint index, TOcFormatInfo far* fmt);

Description

GetFormat returns a Clipboard format with the given index. The index is the Clipboard format number used in the registration table.


TOcLinkView::GetFormatData

TOcLinkView

Syntax

HANDLE _IFUNC GetFormatData(TOcFormatInfo far*);

Description

Request native data for pasting into client application. This function is called only at paste time and not at copy time.


TOcLinkView::GetPartSize

TOcLinkView

Syntax

HRESULT _IFUNC GetPartSize(TSize far*);

Description

Gets the size of the part object.


TOcLinkView::Open

TOcLinkView

Syntax

HRESULT _IFUNC Open(bool open);

Description

If open is true, Open invokes the server to initiate an out-of-place editing session. That is, it asks the server to execute its Open verb. If open is false, the function tells the server to hide its open editing window but does not end the session.


TOcLinkView::QueryObject

See also	TOcLinkView

Syntax

HRESULT QueryObject(const IID far& iid, void far* far* iface);

Description

Does query on its aggregated helper objects.


TOcLinkView::SetPartPos

TOcLinkView

Syntax

HRESULT _IFUNC SetPartPos(TRect far*);

Description

Sets the position of the selections.


TOcLinkView::SetPartSize

TOcLinkView

Syntax

HRESULT _IFUNC SetPartSize(TSize far*);

Description

Sets the size of the selection.


TOcViewCollection class

See also	Linking and Embedding Classes

Header File

oclink.h

Description

Manages a set of TOcLinkView objects. Every TOcDocument creates a link view collection object to maintain the set of link views associated with the document. The view collection object adds views, deletes views, finds them, counts them, and generally helps the document keep track of what views it has.

Because TOcDocument contains a view collection object, usually you do not have to create or manipulate the collection directly yourself.

Public Constructors and Destructors

TOcViewCollection

~TOcViewCollection

Public Member Functions

Add

Clear

Count

delete

Detach

Find

Find

IsEmpty


TOcViewCollection::TOcViewCollection

TOcViewCollection

Constructor

TOcViewCollection();

Destructor

~TOcViewCollection();

Description

Creates an empty collection. Call Add to insert link views into the collection.

Destructor

Releases all the servers that supply the link views in this collection.


TOcViewCollection::Add

See also	TOcViewCollection

Syntax

int Add(TOcLinkView* const& View);

Description

Adds a new link view to the collection. Returns 1 for success and 0 for failure.


TOcViewCollection::Clear

TOcViewCollection

Syntax

void Clear();

Description

Disconnects all the link views in the collection from their servers, removes them from the collection, and releases them. Tells OLE that this collection has no further need for the servers.


TOcViewCollection::Count

TOcViewCollection

Syntax

virtual unsigned Count();

Description

Returns the number of link views currently in the collection.


TOcViewCollection::Delete

TOcViewCollection

Syntax

void operator delete(void* ptr);

Description

Deletes a link view object (ptr) from the collection.


TOcViewCollection::Detach

See also	TOcViewCollection

Syntax

int Detach(TOcLinkView* const& view, int del = 0);

Description

Removes this link view from the collection. If del is nonzero, then Detach also releases the TOcLinkViewobject. If the view's internal reference count reaches zero as a result, the view deletes itself. Returns 1 for success and 0 for failure.


TOcViewCollection::Find

See also	TOcViewCollection

Syntax 1

unsigned Find(TOcLinkView* const& view);

Description

Searches for view and returns its position in the collection. If view is not in the collection, Find returns UINT_MAX.

Syntax 2

TOcLinkView* Find(TString const moniker) const;

Description

Search for the view with the given moniker and returns a pointer to the view. If the view is not in the collection, Find returns 0.


TOcViewCollection::IsEmpty

TOcViewCollection

Syntax

int IsEmpty();

Description

Returns true if the collection currently contains no objects and false if it contains at least one object.


TOcViewCollectionIter class

See also	Linking and Embedding Classes

Header File

oclink.h

Description

A view collection iterator enumerates the views of a compound document. A compound document can have many views. Within the container, each object is represented by an object of type TOcPart. To manage all the views it contains, TOcDocument creates a collection object of type TOcViewCollection. The collection object takes care of adding and deleting members of the collection. In order to walk through the current list of its views, TOcDocument also creates a view collection iterator. An iterator basically points to an element in the collection. You can increment the iterator to walk through the list of objects. The iterator signals when it reaches the end (the ++ operator returns 0).

Together the collection and its iterator give the document much flexibility in managing its objects.

Public Constructor

TOcViewCollectionIter

Public Member Functions

operator ++

operator ++

Current

int

Restart

Restart


TOcViewCollectionIter::TOcViewCollectionIter

See also	TOcViewCollectionIter

Syntax

TOcViewCollectionIter(const TOcViewCollection& c);

Description

Constructs an iterator to enumerate the view objects contained in the collection c.


TOcViewCollectionIter::operator ++

TOcViewCollectionIter

Syntax 1

TOcLinkView* operator ++;

Description

Returns the current view and then advances the iterator to point to the next view (post-increment).

Syntax 2

TOcLinkView* operator ++(int);

Description

Advances the iterator to point to the next view in the list and then returns that view (pre-increment).


TOcViewCollectionIter::Current

TOcViewCollectionIter

Syntax

TOcLinkView* Current() const;

Description

Returns the view that the iterator currently points to.


TOcViewCollectionIter::operator int

TOcViewCollectionIter

Syntax

operator int() const;

Description

Converts the iterator to an integer value in order to test whether the iterator has finished enumerating the collection. Returns zero if the iterator has reached the end of the list and a nonzero value if it has not.


TOcViewCollectionIter::Restart

TOcViewCollectionIter

Syntax 1

void Restart();

Description

Resets the iterator to begin again with the first view of the document.

Syntax 2

void Restart(unsigned start, unsigned stop);

Description

Resets the iterator to enumerate a partial range of views of the document, beginning with the object at position start in the list and ending with the object at position stop.


TOcFormatInfo struct

See also	Linking and Embedding Structs

Header File

ocf/ocobject.h

Description

Holds information describing a Clipboard format. Used for communicating with the BOCOLE support library. In ObjectComponents, each TOcView object keeps a list of the data formats it supports in a TOcFormatList object. The list contains TOcFormat items where the view records its preferences for each data format. The calls that communicate data format information to the support library place the information in TOcFormatInfo structures.

Clipboard format data is managed for you inside the TOcApp and TOcView objects. Normally you don't need to use this structure directly.

Public Data Members

Name

ResultName

Id

Medium

IsLinkable


TOcFormatInfo::Id

See also	TOcFormatInfo

Syntax

WORD Id;

Description

Holds the number that identifies a Clipboard format. For standard formats, the ID is a constant such as CF_TEXT. For custom formats, it is the value returned by RegisterClipboardFormat.


TOcFormatInfo::IsLinkable

TOcFormatInfo

Syntax

bool IsLinkable;

Description

Holds true if the view lets data in this format be the source for a linked object and false if it does not.


TOcFormatInfo::Medium

See also	TOcFormatInfo

Syntax

uint Medium;

Description

Indicates the transfer mechanism the view uses to send or receive data in this format. Possible values for Medium are defined as ocrxxxx medium constants.


TOcFormatInfo::Name

TOcFormatInfo

Syntax

OLECHAR Name[32];

Description

Holds a string naming the format. OLECHAR changes to a wide character if UNICODE is defined.


TOcFormatInfo::ResultName

TOcFormatInfo

Syntax

OLECHAR ResultName[32];

Description

Holds a string describing the format for the user. OLECHAR changes to a wide character if UNICODE is defined.


TOcInitInfo class

See also	Linking and Embedding Structs

Header File

ocf/ocobject.h

Description

TOcInitInfo holds information that tells ObjectComponents how to create a new part. When the user pastes, inserts, or drops an object into a container, ObjectComponents creates a TOcInitInfo object, initializes it with information about the incoming OLE object, and passes the info object to the TOcPart constructor. The info object tells the part where to find its data and how to create itself.

If you are using ObjectWindows, TOleWindow manages these details for you. If you are programming without ObjectWindows, you can find sample code for using TOcInitInfo objects in the TOleWindow methods that insert objects: look at the code for CmEditInsertObject and CmEditPasteSpecial.

Public Data Members

IBContainer far* Container;

HICON HIcon;

TOcInitHow How;

IStorage far* Storage;

TOcInitWhere Where;

union {

  IDataObject* Data;

  LPCOLESTR Path;

  BCID CId;

  struct{

    HANDLE Data;

    uint DataFormat;

  } Handle;

};

Public Constructors

TOcInitInfo(IBContainer far* container);

TOcInitInfo(TOcInitHow how, TOcInitWhere where, IBContainer far* container);

Public Member Functions

uint32 ReleaseDataObject();


TOcInitInfo::Container

See also	TOcInitInfo

Syntax

IBContainer far* Container;

Description

Container is the view object that is about to receive the object. IBContainer is an undocumented custom OLE interface defined in the BOCOLE support library and implemented in TOcView. The Container data member can hold an object of type TOcView.


TOcInitInfo::HIcon

TOcInitInfo

Syntax

HICON HIcon;

Description

HIcon holds the icon to draw if the user chooses the Display As Icon option from the Insert Object dialog box. The HIcon handle is actually a global memory handle to a metafile containing the icon. The Browse and BrowseClipboard functions in TOcApp handle the Insert Object dialog box for you, so usually you do not need to display the icon directly yourself.


TOcInitInfo::How

See also	TOcInitInfo

Syntax

TOcInitHow How;

Description

Tells whether the object should be linked or embedded when it is added to the document.


TOcInitInfo::Storage

TOcInitInfo

Syntax

IStorage far* Storage;

Description

Storage is the storage object in a compound file. The container provides the storage to hold data transferred from the server. IStorage is a standard OLE interface. ObjectComponents implements the IStorage interface in TOcStorage, so Storage usually holds a TOcStorage object.


TOcInitInfo::Where

See also	TOcInitInfo

Syntax

TOcInitWhere Where;

Description

Tells where the server will place the object's data. For example, the server can choose to transfer data by placing it in a file, in a storage, or in a memory handle.


TOcInitInfo::CId

See also	TOcInitInfo

Syntax

BCID CId;

Description

One of four data fields in an anonymous union, this field is used when Where is iwNew indicating that the incoming object is brand new, being freshly created. CId is the class ID that the server registered for one of its document factories. It tells the server what kind of object to create.


TOcInitInfo::Data

TOcInitInfo

Syntax

IDataObject* Data;

Description

One of four data fields in an anonymous union, this field is used when Where is iwDataObject indicating that the server has created an OLE data object to transfer the data for the incoming object. Data points to the IDataObject interface on the server's data transfer object. (IDataObject is a standard OLE interface.) This is the normal transfer method for objects received from the Clipboard or through a drag-and-drop operation.


TOcInitInfo::Handle

TOcInitInfo

Syntax

struct{

  HANDLE Data;

  uint DataFormat;

} Handle;

Description

One of four data fields in an anonymous union, this structure is used when Where is iwHandle indicating that the server has placed the data for the incoming object in a memory handle. Data is the handle itself and DataFormat identifies a Clipboard format for the data in the handle.


TOcInitInfo::Path

TOcInitInfo

Syntax

LPCOLESTR Path;

Description

One of four data fields in an anonymous union, this field is used when Where is iwFile indicating that the server has placed the data for the incoming object in a file. Path points to the name of the file where the data is stored.


TOcInitInfo Public Constructors

TOcInitInfo

Form 1

TOcInitInfo(IBContainer far* container);

Form 2

TOcInitInfo(TOcInitHow how, TOcInitWhere where, IBContainer far* container);

Description

Both forms of the constructor create a TOcInitInfo object for placing a new part in container. container is the view that will hold the new part. IBContainer is a custom OLE interface defined in the BOCOLE support library and implemented in TOcView. container can be an object of type TOcView.

Form 1: Use Form 1 when invoking the server to create a new object from scratch—for example, when processing the Insert Object command. The new part will be embedded, not linked.

Form 2: Use Form 2 when creating a part to hold an object that already exists—for example, when loading a part from a storage in a compound document. how tells whether the object will be linked or embedded. where tells what medium the server will use to transfer data from the existing object.


TOcInitInfo::ReleaseDataObject

See also	TOcInitInfo

Syntax

uint32 ReleaseDataObject();

Description

If the TOcInitInfo object holds a pointer to the data object from which the new part is about to be created, then ReleaseDataObject decrements the data object's reference count. Call this when you are through with the data object.


TOcAspect enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcAspect

Description

A container uses these values to request that objects in its documents be presented in particular ways. An object might be asked to show all its content, to show a miniature representation of its content, or an icon that represents the type of object it is. A server is not obliged to support all the possible aspects.

The values are flags and can be combined with the bitwise OR operator (|).

Constant	Meaning

asContent	Show the full content of the object at its normal size.

asThumbnail	Show the content of the object shrunk to fit in a smaller space.

asIcon	Show an icon representing the type of object.

asDocPrint	Show the object as it would look if sent to the printer.

asDefault	Continue to use the last aspect specified.

asMaintain	Preserve the object's original aspect ratio. Do not alter the aspect ratio to fit the rectangle where the client chooses to show the object.


TOcDialogHelp enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcDialogHelp

Description

The TOC_APPDIALOGHELP event tells the container when the user clicks the Help button in a standard OLE dialog box. The lParam of the WM_OCEVENT message carries one of these values to indicate which dialog box the user has open.

Constant	Dialog Box	Purpose

dhBrowse	Insert Object dialog box	Choose an object to insert.

dhBrowseClipboard	Paste Special dialog box	Choose the data format for pasting an object.

dhConvert	Convert dialog box	Convert an object to work with a different server.

dhBrowseLinks	Links dialog box	Update links to objects.

dhChangeIcon	Change Icon dialog box	Used internally by Insert Object and Paste Special dialog boxes.

dhFileOpen	File Open dialog box	Choose a file to open.

dhSourceSet	Change Source dialog box	Assign a new link source to a linked object.

dhIconFileOpen	File Open dialog box	Confirm that the chosen file contains an icon resource.


TOcDropAction enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcDropAction

Description

TOcApp::Drag uses these values to describe what actions are allowed and what actions actually occur during a drag and drop operation. The values are flags and can be combined with the bitwise OR operator (|).

Constant	Meaning

daDropCopy	Copy the object to the drop site.

daDropMove	Move the object to the drop site.

daDropLink	Create a link to the object at the drop site.

daDropNone	No action occurred.


TOcInitHow enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcInitHow

Description

These values tell whether a container is to link or embed a new object it is receiving. The container passes this information to a TOcInitInfo object when it receives a new OLE object.

Constant	Meaning

ihLink	Link to the object. Create a reference in the container's document that points to the place in the server's document where the data actually resides.

ihEmbed	Embed the object. Copy the object's data directly into the container's document.

ihMetafile	Embed a static object that draws itself as a metafile.

ihBitmap	Embed a static object that draws itself as a bitmap.


TOcInitWhere enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcInitWhere

Description

These values tell where the data for an object resides. A container passes this information to a TOcInitInfo object when it receives a new OLE object for linking or embedding. The server can choose any of several available channels for transferring the data in the object.

Constant	Meaning

iwFile	The server passes the data in a disk file.

iwStorage	The server passes the data in a storage object (part of a compound file).

iwDataObject	The server passes the data in a data transfer object, one that supports the standard IDataObject OLE interface. (Objects transferred through the Clipboard or by dragging support this interface. TOcInitInfo holds a pointer to the interface.)

iwNew	The server will be asked to create a new object.

iwHandle	The server passes a memory handle for the data.


TOcInvalidate enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcInvalidate

Description

Functions that invalidate an object use these enumeration values to indicate whether the data in the object has changed or the appearance of the object has changed. It is possible for the data in an object to change without invalidating the view of the object. For example, if the object is drawn as an icon, then editing the data probably does not call for an update to the view. If both the data and the view change, then combine both flags with the bitwise OR operator (|).

If the view is invalid, the object needs to be redrawn. If the data is invalid, then the object needs saving. (It is not necessary to save the object right away. invData simply indicates that the object is dirty and needs to be saved before the document is closed.)

Constant	Meaning

invData	The data in an object has changed and should be updated in the container.

invView	The appearance of an object needs to change and should be updated in the container.


TOcPartName enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcPartName

Description

When a container asks the server for the name of a part, it might want any of several possible answers. These values indicate which name the container wants to see.

Constant	Meaning

pnLong	The string the server registered as the description for this type of object.

pnShort	The string the server registered as the progid for this type of object.

pnApp	The string the server registered as the description for the server application as a whole.


TOcMenuEnable enum

See also	Linking and Embedding Enums

Syntax

enum TOcMenuEnable

Description

These enumeration values are flags that can be combined with the bitwise OR operator (|). A container passes them to the TOcApp::EnableEditMenu function in order to determine which OLE commands on the Edit menu should be enabled. The answer depends on whether the container supports any of the data formats currently present on the Clipboard.

Constant	Menu Command Enabled

meEnablePaste	The Paste command places an object from the Clipboard in the open document. The format of the new data object depends on what the server prefers and the container supports.

meEnablePasteLink	The Paste Link command adds to the open document a link to the object on the Clipboard.

meEnableBrowseClipboard	The Paste Special command invokes a standard dialog box that shows all the data formats available for the object currently on the Clipboard and lets the user choose among them.

meEnableBrowseLinks	The Links command displays a list of all the linked objects in the open document, allowing the user to update or delete them.


TOcScrollDir enum

See also	Linking and Embedding Enums

Header File

ocf/ocobject.h

Syntax

enum TOcScrollDir

Description

The OC_VIEWSCROLL event tells the container when the user performs a drag movement that should scroll the window. The lParam of the WM_OCEVENT message carries one of these values to indicate which direction the window has been asked to scroll.

Constant	Meaning

sdScrollUp	Scroll toward the top of the document.

sdScrollDown	Scroll toward the bottom of the document.

sdScrollLeft	Scroll toward the left edge of the document.

sdScrollRight	Scroll toward the right edge of the document.


TOcMenuDescr struct

See also	Linking and Embedding Structs

Header File

ocf/ocapp.h

Description

The menu descriptor structure is used when merging the menus of a container and server for in-place editing. The structure holds a handle to a shared Windows menu object and a count of the number of drop-down menus in each group.

If you are using ObjectWindows, use the information in the structure to construct a TMenuDescr object for the other application. To merge two menus, call TMenuDescr::Merge. If you are not using ObjectWindows, call the Windows API routines such as InsertMenu to place your own commands in the shared menu.

The following messages carry a TOcMenuDescr struct in their lParams: OC_APPINSMENUS, OC_APPMENUS, and OC_VIEWINSMENUS. The ObjectWindows OLE-enabled window and view classes process these messages for you. Unless you are programming without ObjectWindows, you usually will not have to use TOcMenuDescr directly. For examples of how to process the messages, see the source code for the relevant event handlers in TOleView, TOleWindow, TOleFrame, and TOleMDIFrame.

Public Data Members

HMENU HMenu;

int Width[6];


TOcMenuDescr::HMenu

TOcMenuDescr

Syntax

HMENU HMenu;

Description

Holds a handle to the shared menu. The handle is valid only while the menu is constructed. Do not store it for later use.


TOcMenuDescr::Width

See also	TOcMenuDescr

Syntax

int Width[6];

Description

The Width array contains the number of pop-up menus in each menu group. The groups, in order, are File, Edit, Container, Object, Windows, and Help.

The array is meant to help you construct a  object. The numbers it holds control how the menu is merged.


TOcPart class

See also	Linking and Embedding Classes

Header File

ocf/ocpart.h

Base Class

TUnknown

Description

A TOcPart object represents a linked or embedded object in a document as the container sees it. From the server's side, the same linked or embedded OLE object has two parts: data (TOcDocument) and a graphical representation of the data (TOcRemView). TOcPart manages a site in the container's document where a server places an OLE object.

TOcPart is a COM object and implements the IUnknown interface.

Public Constructors

TOcPart

Public Member Functions

operator ==

Activate

CanOpenInPlace

Close

Delete

Detach

DoVerb

Draw

EnumVerbs

FinishLoading

GetName

GetNameLen

GetPos

GetRect

GetServerName

GetSize

GetStorage

Init

IsActive

IsLink

IsSelected

IsVisible

IsVisible

Load

Open

OpenInPlace

Rename

Save

Save

Select

SetActive

SetFormatData

SetHost

SetPos

SetSize

SetStorage

SetVisible

Show

UpdateRect

Protected Member Functions

InitObj

Protected Data Members

Flags

Name

OcDocument

Pos

Size

Storage

TFlag


TOcPart::TOcPart

See also	TOcPart

Syntax 1

TOcPart(TOcDocument& document, TOcInitInfo far& initInfo, TRect pos, int id = 0);

Description

document is the container's TOcDocument object representing the compound document that will hold the newly created part. initInfo contains information about the object being inserted. It is usually obtained during a paste, drop, or insertion operation. The coordinates in pos designate the area where the new object will be drawn. id is any arbitrary unique integer used to distinguish this object from others in the same document. If id is 0, TOcPart generates a new ID automatically.

Syntax 2

TOcPart(TOcDocument& document, const char far* name);

Description

document is the same as for Form 1. The name string is the name of a linked or embedded part. The second form is used when loading a part from a compound document. The name of the part is also the name of the storage where the part was written.

Syntax 3

TOcPart(TOcInitInfo far* initInfo, TRect pos);

Description

initInfo contains information about the object being inserted. It is usually obtained during a paste, drop, or insertion operation. The coordinates in pos designate the area where the new object will be drawn.

Syntax 4

TOcPart(TOcDocument& document, int id = 0);

Description

document is the container's TOcDocument object representing the compound document that will hold the newly created part. id is any arbitrary unique integer used to distinguish this object from others in the same document. If id is 0, TOcPart generates a new ID automatically.


TOcPart::operator ==

TOcPart

Syntax

bool operator==(const TOcPart& other);

Description

Returns true if other is the same TOcPart as this. This operator is defined for the use of the TOcPartCollection class.


TOcPart::Activate

See also	TOcPart

Syntax

bool Activate(bool activate);

Description

If activate is true, this function activates the part by asking the server to execute its primary (or default) verb for the object. If the default verb is Edit, for example, Activate initiates an in-place editing session. If activate is false, then this function de-activates an in-place editing session.

Activate returns true if the server is able to execute the command.


TOcPart::CanOpenInPlace

Syntax

bool CanOpenInPlace();

Description

Returns a value indicating whether the part can be opened in place.


TOcPart::Close

TOcPart

Syntax

bool Close();

Description

Disconnects the embedded object from its server. Returns true if the server closes successfully.


TOcPart::Delete

See also	TOcPart

Syntax

void Delete();

Description

Delete is used when the user selects an embedded object and presses the Del key (or does a cut operation.) It first calls Close to disconnect the container from the embedded object. Then it releases the reference to the embedded part.


TOcPart::Detach

TOcPart

Syntax

int Detach();

Description

Separates a part from its document. Call Detach before cutting a part to the Clipboard, for example.


TOcPart::DoVerb

See also	TOcPart

Syntax

bool DoVerb(uint whichVerb);

Description

Tells the server to execute one of its commands on the part. A verb is usually an action such as Edit or Play. One server can support several verbs, and whichVerb identifies a particular verb by its ordinal value. (The first verb, the primary or default verb, is zero). DoVerb returns true if the server is able to complete the requested action. Executing a verb can cause the part to become activated.


TOcPart::Draw

See also	TOcPart

Syntax

bool Draw(HDC dc, const TRect& pos, const TRect& clip, TOcAspect aspect = asDefault);

Description

Draws the part on the screen. If the part has not yet been loaded, Draw loads it first.

dc is a Windows device context where the part is to be drawn. The coordinates in pos tell where in the window to place the part. The clip rectangle designates an area outside of which the server cannot draw. clip and pos can be the same. If clip describes an empty rectangle, then the server can draw anywhere. aspect controls how the data were presented—as an icon, for example.


TOcPart::EnumVerbs

TOcPart

Syntax

bool EnumVerbs(const TOcVerb& verb);

Description

Call EnumVerbs to find out what verbs the server supports for a particular part. Each call to EnumVerbs places another verb in the verb parameter. When all the server's verbs have been enumerated, EnumVerbs returns false.

TOleWindow calls EnumVerbs in order to place verbs for the active object on the container's Edit menu.


TOcPart::FinishLoading

See also(!ALink(TOcInitInfo;TOcPart_InitObj, 2) 	TOcPart

Syntax

void FinishLoading();

Description

Loads an embedded object by constructing a TOcInitInfo object for the active view and passing the TOcInitInfo object to the InitObj function.


TOcPart::GetName

See also	TOcPart

Syntax

TString GetName();

Description

Returns the string that identifies the part. Every part in a document has a different name. ObjectComponents creates the names for you automatically by incrementing an internal ID number for each new part.


TOcPart::GetNameLen

See also	TOcPart

Syntax

int GetNameLen();

Description

Returns the number of characters in the name string that identifies the part. The count does not include the terminating null character.


TOcPart::GetPos

See also	TOcPart

Syntax

TPoint GetPos() const;

Description

Returns the part's position within its container document. The position specifies the part's upper left corner in client area coordinates. The coordinates take into account any scaling set for the TOcView object that holds the part.


TOcPart::GetRect

See also	TOcPart

Syntax

TRect GetRect() const;

Description

Returns the rectangle that bounds the image of the part in the container's client area. The position of the rectangle is given in client area coordinates.


TOcPart::GetServerName

See also	TOcPart

Syntax

LPCOLESTR GetServerName(TOcPartName partName);

Description

Asks OLE for the name of the object or of the object's server, depending on the value of partName. A container might want to display this information in its title bar.

In the current implementation of ObjectComponents, this function is not used. The TOcView object automatically updates the container window title.


TOcPart::GetSize

See also	TOcPart

Syntax

TSize GetSize() const;

Description

Returns the size of the part's image in the container document. The fields of the return value give the width and height of the part in client area coordinates. If there is scaling, the coordinates take that into account.


TOcPart::GetStorage

TOcPart

Syntax

TOcStorage* GetStorage();

Description

Returns the storage pointer for the part.


TOcPart::Init

See also	TOcPart

Syntax

virtual bool Init(TOcInitInfo far* initInfo, TRect pos);

Description

Initializes the Pos and Size data members. Calls the EvOcViewSetSiteRect function of the ContainerHost data member. Calls the InitObj function. Adds the part to the document part list. (The document is stored in the OcDocument data member.)


TOcPart::IsActive

See also	TOcPart

Syntax

bool IsActive() const;

Description

Returns true if the part is currently active and false if it is not.


TOcPart::IsLink

TOcPart

Syntax

bool IsLink() const;

Description

Returns true if the part represents a linked OLE object and false if it represents an embedded OLE object. A container might use this method to distinguish visually between linked and embedded objects. For an example, look at the source code for TOleWindow::PaintParts.


TOcPart::IsSelected

See also	TOcPart

Syntax

bool IsSelected() const;

Description

Returns true if the part is currently selected and false if it is not. This function is frequently called in loops that process all the selected objects in a document. For example, when TOleView paints the parts in a document, it calls IsSelected for each one to determine where to paint selection boxes.

Selection state information is maintained entirely in TOcPart and does not affect the OLE object itself.


TOcPart::IsVisible

See also	TOcPart

Syntax 1

bool IsVisible() const;

Description

Returns true if the part is currently visible and false if it is hidden.

Syntax 2

bool IsVisible(const TRect& logicalRect) const;

Description

Returns true if the part is currently visible within the given logicalRect area of the container's window. Returns false if the part is not visible, perhaps because the user has scrolled to another part of the document.


TOcPart::Load

See also	TOcPart

Syntax

bool Load();

Description

Initializes a TOcPart object with information read from a storage.


TOcPart::Open

See also	TOcPart

Syntax

bool Open(bool open);

Description

If open is true, the Open command invokes the server to initiate an out-of-place editing session. More specifically, it asks the server to execute its Open verb. If open is false, the command tells the server to hide its open editing window but does not end the session.

Open returns true for success. If the server does not support editing, Open returns false.

Note:	TOcPart::Close is not the opposite of TOcPart::Open. To terminate editing, pass false to Open.


TOcPart::OpenInPlace

TOcPart

Syntax

HWND OpenInPlace(HWND hwnd);

Description

Opens the part in place. hwnd is the handle for the part’s window.


TOcPart::Rename

See also	TOcPart

Syntax

void Rename();

Description

Causes the part to update the internal name that ObjectComponents generates to distinguish the parts in a document. Call Rename whenever you rename the document's file. OLE uses the object's name when creating links, so the object name must accurately reflect the file name in order for links to work.


TOcPart::Save

See also	TOcPart

Syntax 1

bool Save(bool sameAsLoad = true, bool remember = true);

Description

Causes the part to write itself into the document's file stream. If sameAsLoaded is true, then the part saves itself in the same storage where it was last written. Setting sameAsLoaded to false causes the part to create a new storage for itself under the document's new root storage. Usually sameAsLoaded should be true in response to a File|Save command and false in response to File|Save As.

(A storage is a compartment within a compound file. ObjectComponents manages the storages for you. Usually you do not have to give explicit instructions about where to store parts.)

Syntax 2

bool Save(IStorage* storage, bool sameAsLoad, bool remember);

Description

The second form accepts a pointer to an IStorage interface, allowing you to control where the object is written. sameAsLoaded is the same as in Form 1. remember tells the part whether or not to remember the object in storage. When saving a part to its usual file, you typically want it to remember its own storage. When copying a part, on the other hand, you typically want the part to keep its original storage object, not the one where you are saving the copy. When saving a copy to a file for the Clipboard, for example, remember should be false.


TOcPart::Select

See also	TOcPart

Syntax

void Select(bool select);

Description

Tells the part whether or not it is currently selected. Make select true to select the part and false to deselect it. The user selects objects in order to perform operations on them. For example, the user selects an object before copying it to the Clipboard. When TOleView paints its parts, it queries each one and draws a selection box around any that the user has selected.


TOcPart::SetActive

See also	TOcPart

Syntax

void SetActive();

Description

Synchronizes an internal flag with the object's actual state: active or inactive. Usually you should not have to call this function. To make a part active, call TOcPart::Activate instead.


TOcPart::SetFormatData

See also	TOcPart

Syntax

bool SetFormatData(TOcFormatInfo far* fmt, HANDLE data, bool release);

Description

Sets the data for the server object.


TOcPart::SetHost

TOcPart

Syntax

bool SetHost(IBContainer far* container);

Description

Moves the part from one container to another. container can be an object of type TOcView (or one derived from TOcView). It designates the view that receives the part. SetHost is not usually called from within the application.

IBContainer is a custom interface defined within the BOCOLE support library. TOcView implements this interface.


TOcPart::SetPos

See also	TOcPart

Syntax

void SetPos(const TPoint& pos);

Description

Sets the part's position within its container document. The position specifies the part's upper left corner in pixels measured from the upper left corner of the container's client window. If there is scaling, the coordinates take that into account.


TOcPart::SetSize

See also	TOcPart

Syntax

void SetSize(const TSize& size);

Description

Sets the size of the part's image in the container document. size sets the width and height of the part in client area coordinates. The coordinates take into account any scaling set for the TOcView object that holds the part.


TOcPart::SetStorage

Syntax

void SetStorage(IStorage* storage, bool remember =true);

Description

Sets the storage pointer for the part.


TOcPart::SetVisible

See also	TOcPart

Syntax

void SetVisible(bool visible);

Description

Shows or hides the part, according to the value of visible.


TOcPart::Show

See also	TOcPart

Syntax

bool Show(bool show);

Description

Makes the part visible. Show is used to ask the Link Source to show itself in the container window. If show is false, the part hides itself. The return value is true for success.


TOcPart::UpdateRect

See also	TOcPart

Syntax

void UpdateRect();

Description

Sets the part to a new rectangle when its size or position changes. It is called by SetPos and GetRect.


TOcPart::~TOcPart

TOcPart

Syntax

~TOcPart();

Destructor

Destroys the TOcPart object.


TOcPart::InitObj

TOcPart

Syntax

virtual bool InitObj(TOcInitInfo far* initInfo);

Description

Initializes internal helper objects. Makes the part active.


TOcPart::Flags

See also	TOcPart

Syntax

uint16 Flags;

Description

Holds information about the part as TFlag enum settings.


TOcPart::Name

TOcPart

Syntax

string Name;

Description

The name of the part.


TOcPart::OcDocument

TOcPart

Syntax

TOcDocument& OcDocument;

Description

The document that contains the part.


TOcPart::Pos

TOcPart

Syntax

TPoint Pos;

Description

The position of the part.


TOcPart::Size

TOcPart

Syntax

TSize Size;

Description

The size of the part.


TOcPart::Storage

TOcPart

Syntax

TOcStorage* Storage;

Description

The storage pointer for the part.


TOcPart::TFlag

TOcPart

Syntax

enum TFlag;

Description

Flags that represent the current state of the part:

Flag	Description

Visible	The part is visible.

Selected	The part is selected.

Active	The part is active.

Link	The part is a link.

Closing	The part is closing.

OcxDefault	The part is an OCX default control. (Like an OK button on a dialog box.)

OcxCancel	The part is an OCX cancel control. (Like a Cancel button on a dialog box.)


TOcPartCollection class

See also	Linking and Embedding Classes

Header File

ocf/ocpart.h

Description

Manages a set of TOcPart objects. Every TOcDocument creates a part collection object to maintain the set of OLE objects linked or embedded in the document. The part collection object adds parts, deletes parts, finds them, counts them, and generally helps the document keep track of what it has.

Because TOcDocument contains a part collection object, usually you do not have to create or manipulate the collection directly yourself.

Public Constructor

TOcPartCollection

Public Member Functions

Add

Clear

Count

Detach

Find

IsEmpty

Locate

SelectAll


TOcPartCollection::TOcPartCollection

TOcPartCollection

Constructor

TOcPartCollection();

Destructor

~TOcPartCollection();

Description

Creates an empty collection. Call Add to insert parts in the collection.

Destructor

Releases all the servers that supply the linked or embedded objects.


TOcPartCollection::Add

See also	TOcPartCollection

Syntax

int Add(TOcPart* const& part);

Description

Adds a new part to the collection. Returns 1 for success and 0 for failure.


TOcPartCollection::Clear

TOcPartCollection

Syntax

void Clear();

Description

Disconnects all the parts in the collection from their servers, removes them from the collection, and releases them. Tells OLE that this collection has no further need for the servers.


TOcPartCollection::Count

TOcPartCollection

Syntax

virtual unsigned Count() const;

Description

Returns the number of parts currently in the collection.


TOcPartCollection::Detach

See also	TOcPartCollection

Syntax

int Detach(TOcPart* const& part, int del = 0);

Description

Removes part from the collection. If del is nonzero, then Detach also releases TOcPart object. If the part's internal reference count reaches zero as a result, the part deletes itself. Returns 1 for success and 0 for failure.


TOcPartCollection::Find

See also	TOcPartCollection

Syntax

unsigned Find(TOcPart* const& part) const;

Description

Searches for part and returns its position in the collection. If part is not in the collection, Find returns UINT_MAX.


TOcPartCollection::IsEmpty

TOcPartCollection

Syntax

int IsEmpty() const;

Description

Returns true if the collection currently contains no objects and false if it does contain at least one object.


TOcPartCollection::Locate

See also	TOcPartCollection

Syntax

TOcPart* Locate(TPoint& point);

Description

Returns the part object visible at a particular point on the screen. The numbers in point are interpreted as logical coordinates. If no part in the collection occupies the given point, Locate returns 0.


TOcPartCollection::SelectAll

See also	TOcPartCollection

Syntax

bool SelectAll(bool select = false);

Description

Sets the selection state of all the parts in the collection. If select is true, SelectAll selects them all. If select is false, it deselects all the parts. The user can perform actions (such as dragging, deleting, and copying) that affect all the selected objects.

The container conventionally marks selected objects by drawing a rectangle with grapples (handles for moving the rectangle) around each of them. The TOleWindow class does this automatically in ObjectWindows programs.


TOcPartCollectionIter class

See also	Linking and Embedding Classes

Header File

ocf/ocpart.h

Description

A part collection iterator enumerates the objects embedded in a compound document.

A compound document can contain many linked and embedded objects. Within the container, each object is represented by an object of type TOcPart. To manage all the parts it contains, TOcDocument creates a collection object of type TOcPartCollection. The collection object takes care of adding and deleting members of the collection. In order to walk through the current list of its parts, TOcDocument also creates a part collection iterator. An iterator basically points to an element in the collection. You can increment the iterator to walk through the list of objects. The iterator signals when it reaches the end (the ++ operator returns 0).

Together the collection and its iterator give the document much flexibility in managing its objects.

Public Constructor

TOcPartCollectionIter

Public Member Functions

operator ++

operator ++

Current

operator int

Restart

Restart


TOcPartCollectionIter::TOcPartCollectionIter

See also	TOcPartCollectionIter

Syntax

TOcPartCollectionIter(const TOcPartCollection& c)

Description

Constructs an iterator to enumerate the objects contained in the collection.


TOcPartCollectionIter::operator ++

TOcPartCollectionIter

Syntax 1

TOcPart* operator++(int);

Description

Returns the current part and then advances the iterator to point to the next part (post-increment).

Syntax 2

TOcPart* operator++();

Description

Advances the iterator to point to the next part in the list and then returns that part (pre-increment).


TOcPartCollectionIter::Current

TOcPartCollectionIter

Syntax

TOcPart* Current() const;

Description

Returns the part that the iterator currently points to.


TOcPartCollectionIter::operator int

TOcPartCollectionIter

Syntax

operator int() const;

Description

Converts the iterator to an integer value in order to test whether the iterator has finished enumerating the collection. Returns zero if the iterator has reached the end of the list and a nonzero value if it has not.


TOcPartCollectionIter::Restart

TOcPartCollectionIter

Syntax 1

void Restart();

Description

Resets the iterator to begin again with the first part in the document.

Syntax 2

void Restart(unsigned start, unsigned stop);

Description

Resets the iterator to enumerate a partial range of objects in the document, beginning with the object at position start in the list and ending with the object at position stop.


TOcVerb class

See also	Linking and Embedding Classes

Header File

ocf/ocpart.h

Description

Holds information about a single verb that a server supports for its objects.

A verb is an action the server can perform with one of its objects. A server that creates text objects, for example, might support an Edit verb. A server for sound objects might support Edit, Play, and Rewind.

When the user selects an object in a compound document, the container asks the TOcPart object for a list of the verbs it can execute. The container displays the verbs on its Edit menu. The command for enumerating verbs is TOcPart::EnumVerbs.

Whenever the user selects a part, the container modifies its Edit menu by adding an item for manipulating the object. If the object is part of a Quattro Pro spreadsheet, for example, the container adds the command Notebook Object to its Edit menu. If the user selects this command, then the container shows a pop-up menu with the notebook's verbs, Edit and Open.

For an example of how to implement these items on the edit menu, look at the source code for TOleWindow::CeEditObject in OLEWINDO.CPP.

Public Constructor

TOcVerb

Public Data Members

CanDirty;

TypeName;

VerbIndex;

VerbName;


TOcVerb::TOcVerb

TOcVerb

Syntax

TOcVerb();

Description

Creates an empty verb object.


TOcVerb::CanDirty

TOcVerb

Syntax

bool CanDirty;

Description

Is true if executing the verb can modify the object so that it might need to be saved or redrawn afterwards. For example, the CanDirty field of an Edit verb is always true, and the CanDirty field of a Play verb is usually false.


TOcVerb::TypeName

See also	TOcVerb

Syntax

LPCOLESTR TypeName;

Description

Points to the name of the type of object to which this verb belongs. The container usually shows this name in the Object item of its Edit menu. For example, if the user has selected an object inserted from the server in Step 15 of the ObjectWindows tutorial, TypeName is "Drawing Pad," and the container's Edit menu should have an item saying "Drawing Pad." Choosing this item leads to a pop-up menu with all the picture's verbs on it.

The TypeName string comes from the value the server registered for the menuname key in its document registration table.


TOcVerb::VerbIndex

TOcVerb

Syntax

uint VerbIndex;

Description

Holds the index number that identifies this verb in the server's list of possible verbs. The first verb is always 0 and is considered the default verb. If the user double-clicks the object, the container should ask the server to execute its default verb.


TOcVerb::VerbName

TOcVerb

Syntax

LPCOLESTR VerbName;

Description

Points to the name of the verb. This is the string that the container adds to its Edit menu.


TOcPartChangeInfo class

See also

Header File

ocf/ocpart.h

Decsription

The OC_VIEWPARTINVALID event uses this class to carry information to the container's view window when a part needs repainting. The two data members for this class tell what part has changed and whether the change affects just the object's data, just its appearance, or both. The member functions set and query the data member values.

Public Constructor

TOcPartChangeInfo

Public Member Functions

GetPart

GetType

IsDataChange

IsViewChange

SetDataChange

SetPart

SetViewChange

Protected Data Member

Part

Type


TOcPartChangeInfo::TOcPartChangeInfo

See also	TOcPartChangeInfo

Syntax

TOcPartChangeInfo(TOcPart* part, TOcInvalidate type = invView)

Description

part points to the object that has become invalid. type is a bit flag indicating whether the part's data, its appearance, or both are out of date. The possible values are invView and invData.


TOcPartChangeInfo::GetPart

TOcPartChangeInfo

Syntax

TOcPart* GetPart();

Description

Returns a pointer to the part object whose data or appearance are out of date.


TOcPartChangeInfo::GetType

TOcPartChangeInfo

Syntax

int GetType();

Description

Returns the type of change.


TOcPartChangeInfo::IsDataChange

See also	TOcPartChangeInfo

Syntax

bool IsDataChange();

Description

Returns true if the part's data has changed and false if it has not. The result is determined by testing the Type member for the presence of the invData flag.


TOcPartChangeInfo::IsViewChange

See also	TOcPartChangeInfo

Syntax

bool IsViewChange();

Description

Returns true if the part's appearance has changed and false if it has not. The result is determined by testing the Type member for the presence of the invView flag.


TOcPartChangeInfo::SetDataChange

See also	TOcPartChangeInfo

Syntax

SetDataChange();

Description

Call this member to indicate that the data in the part has changed and needs updating. SetDataChange turns on the invData bit in the Type member.


TOcPartChangeInfo::SetPart

See also	TOcPartChangeInfo

Syntax

void SetPart(TOcPart* part);

Description

Call this function to specify the part that has become invalid


TOcPartChangeInfo::SetViewChange

See also	TOcPartChangeInfo

Syntax

void SetViewChange();

Description

Call this member to indicate that the appearance of the part has changed and needs updating. SetDataChange turns on the invView bit in the Type member.


TOcPartChangeInfo::Part

TOcPartChangeInfo

Syntax

TOcPart* Part;

Description

Part holds a pointer to the part object whose view or data has become invalid. Part is set by the constructor or by the SetPart member function.


See Also

TOcPartChangeInfo Public constructor

TOcPartChangeInfo::SetPart


TOcPartChangeInfo::Type

TOcPartChangeInfo

Syntax

int Type;

Description

Type holds bit flags indicating whether the part's data, its appearance, or both have become invalid. Type is set by the constructor SetViewChange or the SetDataChange members. The bit flags, defined in the TOcInvalidate enum, are invView and invData.


ee Also

TOcInvalidate enum

TOcPartChangeInfo Public constructor

TOcPartChangeInfo::SetDataChange

TOcPartChangeInfo::SetViewChange


TComponentFactory typedef
TComponentFactory Type Definition

See also	General OLE Classes, Macros, and Type Definitions

Header file

ocf/ocreg.h

Syntax

typedef IUnknown* (*TComponentFactory)(IUnknown* outer, uint32 options, uint32 id = 0);

Description

TComponentFactory is a type definition for a callback function.

outer points to the IUnknown interface of an external OLE object under which the application is asked to aggregate. If outer is 0, then either the new object is independent or it will become the outer object in an aggregation.

options contains bit flags indicating the application's running state. To test the flags, use the TOcAppMode enum constants.

id is a number ObjectComponents assigns to identify a particular type of object the application can create. If id is 0, the application is asked to create itself. To request particular document types, ObjectComponents passes the document template ID.

The return value is a pointer to the IUnknown interface of whatever object the callback function creates, either the application itself or one of its objects. During aggregation, the return value becomes the inner IUnknown pointer in some other object. (IUnknown is a standard OLE type declared in compobj.h.)

A callback of type TComponentFactory is passed to the constructor of an application's registrar object (either TOcRegistrar for a linking and embedding application or TRegistrar for an application that supports automation only). The easiest way to create a factory callback is with a factory template, such as TOleFactory<>.


TOcAppMode enum

See also	Linking and Embedding Enums

Header File

ocf/ocreg.h

Description

The enumerated values of TOcAppMode represent flags that ObjectComponents sets to indicate an application's running modes. Some flags are set in response to command-line switches that OLE places on a server's command line. Others are set as the application registers itself.

To determine whether a particular mode flag is set, call TOcApp::IsOptionSet or TOcAppHost::IsOptionSet. The TOcApp object holds the mode flags for each instance of the application. TOcAppHost simply queries the TOcApp.

The enumerated values are bit flags and can be combined with the bitwise OR operator (|). Flags marked with an asterisk can differ for each instance of an application.

Constant	What the Server Should Do

amAnyRegOption	Combine the RegServer, UnregServer, and TypeLib bits.

amAutomation	Register itself as single-use (one client only). Always accompanied by -Embedding.

amDebug	Enter a debugging session.

amExeMode	*Nothing. This flag is set to indicate that the server is running as an .EXE. Either the server was built as an .EXE, or it is a DLL that was launched by an .EXE stub and is running as an executable program.

amExeAppHost	Nothing. This flag is set to indicate that the server was built as a .EXE program.

amEmbedding	*Consider remaining hidden because it is running for a client, not for itself.

amLangId	Use the locale ID that follows this switch when creating registration and type libraries. (Useless without the -RegServer or -TypeLib switch.)

amNoRegValidate	Omit the usual validation check comparing the server's progid, clsid, and path to those registered with the system. The registrar object responds to this flag.

amRegServer	Register itself in the system registration database and quit.

amRun	Run its message loop. This is used by the factory callback function.

amServedApp	*Avoid deleting itself (a client is using the application and holds a reference to it).

amShutdown	*When the TComponentFactory callback sees this flag, it should terminate the application.

amSingleUse	*Register itself as a single-use (one client only) application.

amTypeLib	Create and register a type library.

amUnregServer	Remove all its entries from the system registration database and quit.


Ocxxxx Global Functions

See also

Header File

ocf/ocreg.h

Description

ObjectComponents uses these global functions to register applications in the system registration database. They are called during construction of the application's registrar object. Because ObjectComponents performs all the usual registration chores for you, normally you don't need to call these functions directly. They are global, however, so if you need them you can call them without the overhead of creating the registrar and its related internal objects.

If they fail, these functions throw TXRegistry exceptions.

Function	Purpose

OcRegisterClass	Writes all the information from one registration table to an output stream.

OcRegistryUpdate	Merges all the information from an input stream into the registration database.

OcRegistryValidate	Checks whether information in a registration table matches the corresponding information already recorded in the registration database.

OcSetupDebugReg	Takes the information from a registration table and composes a modified registration table for registering a debugging version.

OcUnregisterClass	Removes entries from the system's registration database.

The following pseudocode describes the sequence of events ObjectComponents normally follows to register an application.

for table = 1 to NumTables {

  validate table's registration	// OcRegistryValidate

  if invalid

    write reg entries to output stream	// OcRegisterClass

}

merge stream into registration database	// OcRegistryUpdate


OcRegisterClass function

See also	Ocxxxx Global Functions

Syntax

long OcRegisterClass(TRegList& regInfo, HINSTANCE hInst, ostream& out, TLangId lang, char* filter = 0, TRegItem* defaults = 0, TRegItem* extra = 0);

Description

Writes all the information from a registration table to an output stream. After writing all registration tables to the same output stream, call OcRegistryUpdate to merge the stream with the system registration database. This sequence makes it possible to cancel registration before modifying the registration database if any of the output operations fails.

regInfo is the registration table you want to record. (Registration tables are built with registration macros and conventionally have names like AppReg and DocReg.)

hInst identifies the application AppHost. ObjectComponents uses it to discover the full path to the application's executable in order to provide a default value for the path key.

out is the stream where OcRegisterClass writes the registration information it produces. If you set -RegServer on the application command line and specify a file name, the output stream is sent to the file you specify. Otherwise, it is a temporary buffer in memory.

lang is the locale ID for retrieving localized strings from XLAT resources for registration values.

filter lists registration key templates to process. When filter is zero, the function processes all information in regInfo. A nonzero value restricts processing to just the templates named. For example, the following command limits processing to three templates.

::OcRegisterClass(RegInfo, AppInstance, vstrm, lang, "\001\002\006");

The three templates are the command line, the progid, and the clsid. To find the numbers for particular templates, look for the initialization of the OcRegTemplates[] array in OCREG.CPP.

The example command is used in validating an application's existing registration entries. It writes only three entries to the output stream. ObjectComponents then passes the same stream to OcRegistryValidate determines whether those three entries match those already in the system.

defaults points to an array of TRegItem structures, each holding a key/value pair. If the regInfo table omits any of the keys supplied in defaults, OcRegisterClass automatically writes the missing keys with their default values to the output stream.

extra points to an array of TRegItem structures, each holding a key/value pair. The extra array overrides any  regInfo entries for the same keys.

The return value is the mask of document template flags (dtxxxx constants) written to the output stream for the docflags key.


OcRegistryUpdate function

See also	Ocxxxx Global Functions

Syntax

void OcRegistryUpdate(istream& in);

Description

Merges the information from in with the system registration database. To create the input stream, call OcRegisterClass for each table.


OcRegistryValidate function

See also	Ocxxxx Global Functions

Syntax

int OcRegistryValidate(istream& in);

Description

Searches the registration database for all the registration entries from in. If it finds all the entries, and if all the entries match exactly, the return value is 0. Otherwise, the return value tells how many in entries do not have exact matches in the registration database.

To create the input stream, call OcRegisterClass.


OcSetupDebugReg function

See also	Ocxxxx Global Functions

Syntax

int OcSetupDebugReg(TRegList& regInfo, TRegItem* regDebug, TLangId lang, char* clsid);

Description

Reads registration values from the regInfo structure and builds a new structure containing just the debug entries.

A registration table can contain keys such as debugger and debugprogid that are used only to register a debugging version of the same application--one that launches the server directly into a debugger. The presence of the debugprogid key causes ObjectComponents to register the same table twice, using different clsid values. OcSetupDebugReg creates the TRegList structure for the second entry by replacing the progid and adding the -Debug switch to the command line.

regInfo is the original structure containing debug keys.

regDebug points to a new array that the function creates. The size of the array is DebugRegCount.

lang specifies the language to use when retrieving localized strings from XLAT resources.

clsid is the GUID to assign for the debugging version of the structure. ObjectComponents supplies this value for you. This string overrides the clsid in regInfo.

The return value is nonzero for success. 1 indicates that the value in the clsid parameter was used. -1 indicates that no clsid was passed and regDebug has the same clsid as regInfo.

After creating the debugging registration table, call OcRegisterClass to write the entries to an output stream and OcRegistryUpdate to merge them into the registration database.


OcUnregisterClass function

See also	Ocxxxx Global Functions

Syntax

int OcUnregisterClass(TRegList& regInfo, TRegItem* extra=0);

Description

Removes entries from the system registration database.

regInfo is the table whose entries are to be expunged.

extra points to an array of TRegItem entries supplying default values for keys that might not be present in regInfo.

OcUnregisterClass unregisters only the keys stored in OcUnregParams[]. They are debugclsid, debugprogid, clsid, progid, extension, and permid. With those entries gone, Windows automatically deletes any remaining related entries.


TRegistrar class

See also	Automation Classes

Header File

ocf/ocreg.h

Description

TRegistrar manages all the registration tasks for an application. It processes OLE-related switches on the command line and records any necessary information about the application in the system registration database. If the application is already registered in the database, the registrar confirms that the registered path, progid, and clsid are still accurate. If not, it reregisters the application.

Every ObjectComponents application needs to create a registrar object. If your application supports automation but not linking and embedding, then create a TRegistrar object. To support linking and embedding—alone or along with automation—then create a TOcRegistrar instead. TOcRegistrar extends TRegistrar by connecting the application to the BOCOLE support library interfaces that support linking and embedding.

An application's main procedure usually performs these actions with its registrar:

Construct the registrar, passing it a pointer to the application's factory callback.

Call IsOptionSet to check for options that might affect how the application chooses to start (for example, terminating if the application was invoked simply for registration.)

Call Run to enter the program's message loop.

Public Constructor and Destructor

TRegistrar(TRegList& regInfo, TComponentFactory callback, string& cmdLine, HINSTANCE hInst);

virtual ~TRegistrar();

Public Member Functions

virtual bool CanUnload();

TUnknown* CreateAutoApp(TObjectDescriptor app, uint32 options, IUnknown* outer=0);

TUnknown* CreateAutoObject(const void* obj, const typeinfo& objInfo, const void* app, const typeinfo& appInfo);

TUnknown* CreateAutoObject(TObjectDescriptor obj, TServedObject& app);

virtual void far* GetFactory(const GUID& clsid, const GUID far& iid);

uint32 GetOptions() const;

bool IsOptionSet(uint32 option) const;

void ProcessCmdLine(string& cmdLine);

void ReleaseAutoApp(TObjectDescriptor app);

void RegisterAppClass();

virtual int Run();

void SetOption(uint32 bit, bool state);

virtual void Shutdown(IUnknown* releasedObj, uint32 options);

void UnregisterAppClass();

Protected Data Member

TAppDescriptor& AppDesc;

Protected Constructor

TRegistrar(TAppDescriptor& appDesc);


TRegistrar Public Constructors and Destructors
TRegistrar Public Constructor and Destructor

See also	TRegistrar

Syntax

Constructor

TRegistrar(TRegList& regInfo, TComponentFactory callback, string& cmdLine, HINSTANCE hInst);

Destructor

virtual ~TRegistrar();

Description

regInfo is the application registration structure (conventionally named appReg). callback is the factory callback function that ObjectComponents invokes when it is time for the application to create a document. An ObjectWindows program can use the TOleFactory class to create this callback. cmdLine points to the command line received when the application was invoked. hInst is the application instance. For more a description of TOleFactory, see Factory Template Classes and TOleFactoryBase.

The constructor processes OLE-related switches and removes them from the command line. (Call IsOptionSet to determine what switches were found.) It also initializes some settings from the application registration table. If the application is a DLL, the constructor initializes the global DllRegistrar variable.

Destructor

Deletes objects the registrar maintains internally.


TRegistrar Protected Constructor

See also	TRegistrar

Syntax

TRegistrar(TAppDescriptor& appDesc);

Description

The protected constructor is used only by the derived class TOcRegistrar.TAppDescriptor is a class that both registrar objects (TRegistrar and TOcRegistrar) use internally to hold information about an application.


TRegistrar::CanUnload

TRegistrar

Syntax

virtual bool CanUnload();

Description

Returns true if the application is not currently serving any OLE clients and false otherwise.


TRegistrar::CreateAutoApp

See also	TRegistrar

Syntax

TUnknown* CreateAutoApp(TObjectDescriptor app, uint32 options, IUnknown* outer = 0);

Description

Creates an instance of an automated application. This method is usually called from the application's TComponentFactory callback function.

app is the automation server's primary automated class created from the TAutoObjectDelete<> template.

options contains the application's mode flags. This is usually the same value passed in to the factory callback function. The possible values are enumerated in TOcAppMode.

outer points to the IUnknown interface of an outer component under which the application is asked to aggregate.

The return value points to the new OLE application object.


TRegistrar::CreateAutoObject

See also	TRegistrar

Syntax

Form 1

TUnknown* CreateAutoObject(TObjectDescriptor obj, TServedObject& app);

Form 2

TUnknown* CreateAutoObject(const void* obj, const typeinfo& objInfo, const void* app, const typeinfo& appInfo);

Description

CreateAutoObject asks an automated application to instantiate one of its automated objects. It is usually called from the application's TComponentFactory callback function. Which form you call depends on what information you have to identify the kind of object you want to create.

Form 1: app is the automated OLE application object.

obj is the automated C++ object.

Form 2: app and obj are the same as in Form 1.

objInfo identifies the type of object in obj. appInfo identifies the type of object in app. Both values can be obtained using typeid.


TRegistrar::GetFactory

TRegistrar

Syntax

virtual void far* GetFactory(const GUID& clsid, const GUID far& iid);

Description

Returns a pointer to the factory interface for creating type object indicated by clsid. iid names the particular interface you want to receive. If the registrar is unable to find an iid interface for clsid objects, it returns zero.

ObjectComponents calls a DLL's GetFactory member every time a new client loads the DLL. Usually you do not need to call GetFactory yourself.


TRegistrar::GetOptions

See also	TRegistrar

Syntax

uint32 GetOptions() const;

Description

Returns a 32-bit integer containing bit flags that reflect the application's running mode. Some of the flags are set in response to command-line switches. Others are set directly by ObjectComponents. For a list of the mode flags, see the TOcAppMode enum.


TRegistrar::IsOptionSet

See also	TRegistrar

Syntax

bool IsOptionSet(uint32 option) const;

Description

Returns true if a particular option was set as a flag on the application's command line, and false if the option was not set. The flags are set by the ProcessCmdLine method.

For a list of possible values option can assume, see the TOcAppMode enum.

TOcApp objects also have an IsOptionSet method. In most cases they return the same results. In a DLL server, however, the registrar remembers the set of options that the server originally started with, while TOcApp::IsOptionSet queries the options for the currently active instance of the DLL.

Usually the TOcAppHost object manages the creation of the TOcApp object for you, so to query per-instance options it is easiest to call TOcAppHost::IsOptionSet.


TRegistrar::ProcessCmdLine

See also	TRegistrar

Syntax

void ProcessCmdLine(string& cmdLine);

Description

Locates any OLE-related switches on the application's command line (or passed in to a DLL server from ObjectComponents.) The switches tell the program whether it has been launched independently or as a server, whether it should register or unregister itself, whether to create a type library, and signal other running conditions as well. ProcessCmdLine records the presence of each flag it finds. You can call IsOptionSet to determine the results.

The command line is always processed for you when the registrar object is constructed. Usually you do not need to call this function directly.

cmdLine contains the string of arguments passed to the program on its command line. ProcessCmdLine removes OLE-related switches from the command line. That lets you process cmdLine afterwards for any of your own arguments without worrying about OLE arguments.


TRegistrar::RegisterAppClass

See also	TRegistrar

Syntax

void RegisterAppClass();

Description

Tells OLE that an automated application is up and ready to create an application instance. Has no effect if called from an application that does not support automation.

For convenience, it is recommended that every ObjectComponents application, even those that do not support automation, call RegisterAppClass on starting up and UnregisterAppClass when closing down. This habit is harmless even if sometimes unnecessary and ensures that you will not forget to include registration functions if you later add automation.


TRegistrar::ReleaseAutoApp

See also	TRegistrar

Syntax

void ReleaseAutoApp(TObjectDescriptor app);

Description

This method is used by an application's factory callback function if the application must detach itself from OLE before it can shut down. Detaching the application is necessary when an automated application has registered its application object for its class, allowing the controller to manipulate it.


TRegistrar::Run

See also	TRegistrar

Syntax

virtual int Run();

Description

Call this function to execute your program. If the application was built as an .EXE file, then Run lets the application enter its message loop. If the application was built as a DLL, then Run returns without entering the message loop. DLL servers must wait for OLE to call their factory before they run. The purpose of the Run function is to let you build your applications as either an .EXE or a DLL without having to modify your code.

In .EXE programs, Run performs the following steps:

If the application is automated, call RegisterAppClass.

Call the factory function to create and run the application. The application enters its message loop. (In an DLL server, creating and running are separate steps.)

Call the factory function to shut down the application.

Ensure that the application's TOcApp connector object is properly released.


TRegistrar::SetOption

See also	TRegistrar

Syntax

void SetOption(uint32 bit, bool state);

Description

Modifies the application's running mode flags. bit contains bit flags from the TOcAppMode enum. If state is true, SetOption turns the flags on. If state is false, it turns the flags off. You should never have to call this function because ObjectComponents always maintains the mode flags.


TRegistrar::Shutdown

See also	TRegistrar

Syntax

virtual void Shutdown(IUnknown* releasedObj, uint32 options);

Description

Calls the application's factory function and asks it to make the application stop. Ensures that the application's TOcApp connector object is properly released. In the normal path of execution, the Run command performs the same tasks. Call Shutdown to terminate the application directly.


TRegistrar::UnregisterAppClass

See also	TRegistrar

Syntax

void UnregisterAppClass();

Description

Announces that the application is no longer available for OLE interactions.


TRegistrar::AppDesc

TRegistrar

Syntax

TAppDescriptor& AppDesc;

Description

Holds the application descriptor. ObjectComponents uses an application descriptor internally to manage information about a component. (Like EXEs, each DLL gets an application descriptor of its own.) TAppDescriptor is undocumented because it is used only internally and is subject to change. The registrar classes, TOcRegistrar and TRegistrar, are the supported interfaces to the application descriptor. The registrar constructs the descriptor, and most of its member functions call descriptor functions to perform the work.

Usually you will not need to manipulate this data member directly.


ocrxxxx Aspect Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Description

These constants identify modes of presenting data. A server might be able to draw the same object several different ways, such as displaying its full content, creating a miniature representation of the content, or representing the type of object with an icon.

When a server registers a data format, it also registers the aspects it supports for each format. The values of these constants are flags and can be combined with the bitwise OR operator (|).

Constant	OLE Equivalent	Meaning

ocrContent	DVASPECT_CONTENT	Show the full content of the object at its normal size.

ocrThumbnail	DVASPECT_THUMBNAIL	Show the content of the object shrunk to fit in a smaller space.

ocrIcon	DVASPECT_ICON	Show an icon representing the type of object.

ocrDocPrint	DVASPECT_DOCPRINT	Show the object as it would look if sent to the printer.


ocrxxxx Clipboard Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Description

These constants identify standard data formats for data that applications might share with each other. Use them in the REGFORMAT macro to describe the formats that your documents can import and export.

Constant	Windows Format Name	Meaning

ocrText	CF_TEXT	Array of text characters

ocrBitmap	CF_BITMAP	Device-dependent bitmap

ocrMetafilePict	CF_METAFILEPICT	A Windows metafile wrapped in a METAFILEPICT structure

ocrSylk	CF_SYLK	Symbolic Link Format

ocrDif	CF_DIF	Data Interchange Format

ocrTiff	CF_TIFF	Tag Image File Format

ocrOemText	CF_OEMTEXT	Text containing characters in the original equipment manufacturer's character set (usually ASCII)

ocrDib	CF_DIB	Device-independent bitmap

ocrPalette	CF_PALETTE	GDI palette object

ocrPenData	CF_PENDATA	Data for pen extensions to the operating system

ocrRiff	CF_RIFF	Resource Interchange File Format (often used for multimedia)

ocrWave	CF_WAVE	A sound wave file (uses a subset of the RIFF format)

ocrUnicodeText	CF_UNICODETEXT	Wide-character Unicode text (32-bit only)

ocrEnhMetafile	CF_ENHMETAFILE	Enhanced metafile (32-bit only)

ocrRichText	"Rich Text Format"	RTF tagged text format

ocrEmbedSource	"Embed Source"	OLE object that can be embedded

ocrEmbeddedObject	"Embedded Object"	OLE object that is already embedded

ocrLinkSource	"Link Source"	OLE object that can be linked

ocrObjectDescriptor	"Object Descriptor"	Descriptive information about an OLE object that can be embedded

ocrLinkSrcDescriptor	"Link Source Descriptor"	Descriptive information about an OLE object that can be linked


ocrxxxx Direction Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Description

These constants identify directions for passing data. For example, a server might be able to export and import bitmaps but only import metafiles. In that case, it uses ocrGetSet for the bitmap format and ocrGet for metafiles.

When a server registers a data format, it also specifies whether it can get or set each format.

Constant	Meaning

ocrGet	Imports data in the given format

ocrSet	Exports data in the given format

ocrGetSet	Both exports and imports data in the given format


ocrxxxx Limit Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Description

These constants set the maximum number of verbs and data formats that an application is allowed to register for any one document type. Currently these limits are both set to 8.

Constant	Meaning

ocrVerbLimit	Maximum number of verbs a server can register for a document

ocrFormatLimit	Maximum number of data formats an application can register for a document


ocrxxxx Medium Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Description

These constants identify channels for passing data. A server might be able to pass a particular kind of object as a global memory handle, as a disk file handle, or through a data stream, for example.

When a server registers a data format, it also registers the transfer channels it supports for each format. The values of these constants are flags and can be combined with the bitwise OR operator (|).

Constant	OLE Equivalent	Meaning

ocrHGlobal	TYMED_HGLOBAL	Handle to global memory object

ocrFile	TYMED_FILE	Handle to disk file

ocrIStream	TYMED_ISTREAM	Stream object in a compound file

ocrIStorage	TYMED_ISTORAGE	Storage object in a compound file

ocrGDI	TYMED_GDI	GDI object (such as a bitmap)

ocrMfPict	TYMED_MFPICT	METAFILEPICT structure


ocrxxxx Object Status Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Description

These constants describe how an object behaves when presented in particular aspects. Register these options for documents using the REGSTATUS macro.

The values of these constants are flags and can be combined with the bitwise OR operator (|).

Constant	Meaning

ocrActivateWhenVisible	Applies only if ocrInsideOut is set. Indicates that the object prefers to be active whenever it is visible. The container is not obliged to comply.

ocrCanLinkByOle1	Used only in OBJECTDESCRIPTOR. Indicates that an OLE 1 container can link to the object.

ocrCantLinkInside	This object, when embedded, should not be made the source of a link.

ocrInsertNotReplace	This object, when placed in a document, should not replace the current selection but be inserted next to it.

ocrInsideOut	The object can be activated and edited without having to install menus or toolbars. Objects of this type can be active concurrently.

ocrIsLinkObject	Set by an OLE 2 link for OLE 1 compatibility. The system sets this bit automatically.

ocrNoSpecialRendering	Same as ocrRenderingIsDeviceIndependent.

ocrOnlyIconic	The only useful way the server can draw this object is as an icon. The content view looks like the icon.

ocrRecomposeOnResize	When container site changes size, the server would like to redraw its object. (Presumably the server wants to do something other than scale.)

ocrRenderingIsDeviceIndependent	The object makes no presentation decisions based on the target device. Its presentation data is always the same.

ocrStatic	The object is an OLE static object and cannot be edited.


ocrxxxx Usage Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Description

These constants tell how a server supports concurrent clients. Use them to register the usage key for a server.

Constant	Meaning

ocrSingleUse	One client per application instance

ocrMultipleUse	Multiple clients per application instance

ocrMultipleLocal	Multiple clients supported by separate in-proc server


ocrxxxx Verb Attributes Constants

See also	ocrxxxx Constants

Header File

ocf/ocreg.h

Syntax

enum ocrVerbAttributes

Description

These constants give the container hints about how a verb is used. Register these options for documents using the REGVERBOPT macro.

The values of these constants are flags and can be combined with the bitwise OR operator (|).

Constant	Meaning

ocrNeverDirties	The verb never modifies the object in such a way that it needs to be saved again.

ocrOnContainerMenu	The verb should be displayed on the container's menu of object verbs when the object is active. The standard verbs Hide, Show, and Open should not have this flag set.


ocrxxxx Verb Menu Flags

See also	ocrxxxx Constants

Header

ocf/ocreg.h

Description

These constants describe how a server's verbs should appear on the container's menu. Register these options for documents using the REGVERBOPT macro.

The values of these constants are flags and can be combined with the bitwise OR operator (|).

Constant	Windows Equivalent	Meaning

ocrGrayed	MF_GRAYED	Make the verb appear gray on the menu. This also disables the verb.

ocrDisabled	MF_DISABLED	Disable the verb so the user cannot choose it.

ocrChecked	MF_CHECKED	Place a check by the verb.

ocrMenuBarBreak	MF_MENUBARBREAK	Places the verb in a new column and adds a vertical line to separate the columns.

ocrMenuBreak	MF_MENUBREAK	Places the verb in a new column without separating the columns.


TXRegistry class

See also	ObjectComponents Exception Classes

Header File

ocf/ocdefs.h

Base Class

TXBase

Description

TXRegistry is the exception object that ObjectComponents throws when it encounters an unexpected error while reading from or writing to the system registration database.

The object's Check method is static so that you can call it without actually creating a TXRegistry object. If the parameters you pass indicate an error has occurred, Check creates a TXRegistry object and throws the exception for you.

Public Constructors

TXRegistry(const char* msg, const char* key);

TXRegistry(const TXRegistry& copy);

Public Member Functions

static void Check(long stat, const char* key);

const char* Key;


TXRegistry Public Constructors

See also	TXRegistry

Form 1

TXRegistry(const char* msg, const char* key);

Form 2

TXRegistry(const TXRegistry& copy);

Description

Usually you do not need to construct a registry exception directly. Call Check instead.

Form 1: Creates a registry exception object. msg points to an error message and key points to the name of the registry key that ObjectComponents was processing when the exception occurred.

Form 2: The copy constructor constructs a new registry exception object by copying the one passed as copy.


TXRegistry::Check

TXRegistry

Syntax

static void Check(long stat, const char* key);

Description

Tests the value of stat to determine if an error has occurred and if so throws an exception. stat is the return value from a registration command. key is the name of the key that the registration command was processing.

Check is static so that you can call it without actually creating a TXRegistry object first. If stat is nonzero, then Check creates a TXRegistry object and throws an exception. The exception carries the message string "Registry failure on key: key, ErrorCode = stat."


TXRegistry::Key

TXRegistry

Syntax

const char* Key;

Description

Points to the name of the registration key that ObjectComponents was processing when the exception occurred.


_OCFxxxx Macros

See also	General OLE Classes, Macros, and Type Definitions

Header File

ocf/ocdefs.h

Description

These macros are used internally to declare classes, functions, and data members in ObjectComponents classes. Their definitions vary depending on whether you build a 16- or 32-bit EXE or DLL. Some of them also force the declaration to__huge.

These macros closely match the corresponding _OWLxxxx macros.

Constant	Meaning

_OCFCLASS	Exports or imports classes for DLLs.

_OCFDATA	Exports or imports data members for DLLs.

_OCFFUNC	Exports or imports member functions for DLLs.


TOcRemView class

See Also	Linking and Embedding Classes

Header File

ocf/ocremvie.h

Base Class

TOcView

Description

A linking and embedding server creates a remote view object in order to draw its OLE object in the container's window. TOcRemView only draws the object. To load and save the data in the object, the server also needs to create a TOcDocument object. The document and the remote view together represent an OLE object as the server sees it.

The container creates a TOcPart object for every OLE object it receives. The container's part object communicates with the server's document and view objects through OLE. The part tells the server's view when and where to draw the object. It tells the server's document when and where to load or save the object.

A container creates a single view (TOcView for a standard OLE container or TOcxView for an OCX container) for its compound document. This view can contain parts received from other applications. Each part draws itself by invoking a remote view from its server. Servers create TOcRemView objects. (A TOcRemView object can become a container also, however, if the user embeds objects within objects.)

TOcRemView is a COM object and implements the IUnknown interface.

Public Constructor

TOcRemView

Public Member Functions

Copy

Disconnect

EvClose

EvSetFocus

GetContainerTitle

GetInitialRect

GetKind

GetState

Invalidate

IsOpenEditing

Kind

Load

ReleaseObject

Rename

Save

SetContainerStatusText

SetOpenEditing

State


See Also

ObjectComponents Header Files

TOcDocument

TOcView


TOcRemView::TOcRemView

See Also	TOcRemView

Syntax

TOcRemView(TOcDocument& doc, TOcContainerHost* cs, TOcServerHost* ss, TRegList* regList = 0, IUnknown* outer = 0);

Description

A remote view is always associated with a TOcDocument object. The document loads and saves data in an OLE object, and the remote view draws the data in the container's window. That means the document must always be created first.

You must also create a TOcContainerHost object and/or a TOcServerHost object before creating a TOcRemView object.

Also, in both forms regList is a document registration table. A server that creates different kinds of objects needs several document registration tables, one for each type. The regList parameter determines the type of object that the view represents.

outer points to the IUnknown interface of a master object under which the new object is asked to aggregate itself.

Registration tables are built with the BEGIN_REGISTRATION and END_REGISTRATION macros.

The destructor for TOcRemView is private. ObjectComponents releases the object when it is no longer needed.


See Also

Registration Macros (OWL.HLP)

TAutoObject

TOcDocument


TOcRemView::Copy

TOcRemView

Syntax

virtual bool Copy();

Description

Copies the object to the Clipboard. Returns true for success.


TOcRemView::Disconnect

Syntax

void Disconnect();

Description

Disconnects the view from the parts displayed in it.


TOcRemView::EvClose

TOcRemView

Syntax

void EvClose();

Description

The application's remote view window calls this function when it closes. EvClose disconnects the view from any parts displayed in it.


TOcRemView::EvSetFocus

Syntax

virtual bool EvSetFocus(bool set);

Description

The application’s remote view window calls this function when it receives the focus.


TOcRemView::GetContainerTitle

TOcRemView

Syntax

TString GetContainerTitle();

Description

Asks the container for its name. The server usually includes this string in its own title bar during out-of-place editing (when the user edits a linked or embedded object in the server's own window, not in the container's).


TOcRemView::GetInitialRect

See Also	TOcRemView

Syntax

void GetInitialRect(bool selection = false);

Description

Requests the initial size and position of the area where the server can draw its object. This function initializes Extent, a protected data member that TOcRemView inherits from TOcView.


See Also

TOcView::Extent


TOcRemView::GetKind

Syntax

TKind GetKind() const;

Description

Returns the server kind using a TOcRemView::Kind enum.


TOcRemView::GetState

Syntax

TState GetState() const;

Description

Returns the server state using a TOcRemView::State enum.


TOcRemView::Invalidate

See Also	TOcRemView

Syntax

void Invalidate(TOcInvalidate invalid);

Description

Notifies the container's active view that the server has changed either the contents or the appearance of the object. The invalid parameter indicates what needs changing. It can be invData, invView, or both combined with the OR operator (|). If the container is an ObjectComponents application, its active view generates an OC_VIEWPARTINVALID message.


See Also

OC_VIEWxxxx messages

TOcInvalidate enum


TOcRemView::IsOpenEditing

TOcRemView

Syntax

bool IsOpenEditing() const;

Description

Returns true if the view is currently engaged in an open editing session. Open editing occurs when the user chooses an object's Open verb. Open editing takes place in the server's own frame window, unlike in-place editing, which takes place in the container's window. Remote view objects are used in both kinds of editing.


TOcRemView::Kind

TOcRemView

Syntax

enum TKind;

Description

The server kind:

Constant	Meaning

DontKnow	Don’t know because server has not been initialized.

Embedding	Server is embedded.

LoadFromFile	Server has been loaded from file.

Link	Server has been loaded from a linked file.


TOcRemView::Load

See Also	TOcRemView

Syntax

bool Load(IStorage* storageI);

Description

Reads from storageI information specific to the remote view. This information is part of the data the server stores in the container's file when asked to save an object. Load returns true for success.

IStorage is a pointer to an OLE interface. storageI can be a pointer to a TOcStorage object, the ObjectComponents implementation of that interface.


See Also

TOcRemView::Save


TOcRemView::ReleaseObject

Syntax

virtual void ReleaseObject();

Description

Releases the object.


TOcRemView::Rename

TOcRemView

Syntax

void Rename();

Description

Updates the name string ObjectComponents generates to distinguish the parts in a compound document. TOcRemView calls Rename during construction to find out what the container wants to call the object. It is usually not necessary for you to call Rename directly.


TOcRemView::Save

See Also	TOcRemView

Syntax

bool Save(IStorage* storageI);

Description

Writes to storageI information specific to the remote view. This information becomes part of the object data stored in the container's compound document file. Returns true for success.

IStorage is a pointer to an OLE interface. storageI can be a pointer to a TOcStorage object, the ObjectComponents implementation of that interface.


See Also

TOcRemView::Load


TOcRemView::SetContainerStatusText

TOcRemView

Syntax

bool SetContainerStatusText(const char far* text);

Description

Sets the status text for the container.


TOcRemView::SetOpenEditing

TOcRemView

Syntax

void SetOpenEditing();

Description

Sets the server to open editing mode.


TOcRemView::State

TOcRemView

Syntax

enum TState;

Description

The server state:

Constant	Meaning

Hidden	Hidden and ready to go.

Closing	Shutting down.

OpenEditing	In open-edit mode.

InPlaceActive	Active.


TOcStream class

See also	Compound File I/O Classes

Header File

ocf/ocstorag.h

Description

The TOcStream class encapsulates the methods of OLE's IStream interface. It reads and writes data in compound files.

In compound file I/O, storages are analogous to directories and streams to files. A storage can contain both streams and other storages. Each stream represents a set of data and each substorage is a compartment for more streams.

A TOcStream object always works together with the TOcStorage object that contains it.

The streams within a storage have names, just as files do. A stream's name can contain up to 32 characters, including the terminating null.  Stream names cannot contain the following characters: ! . / \ :.  For more information about names, see the topic Storage Naming Conventions in OLE.HLP.

The OLE definition of IStream includes methods such as Commit and Revert, to allow for operation in transacted mode, where changes are stored in a temporary buffer and become permanent only when committed. The current implementation of OLE supports transacted only for storages, not for streams. At present, TOcStream::Commit and TOcStream::Revert have no effect. The LockRegion and UnlockRegion similarly support features not yet available in OLE.

Commands that return HRESULT values correspond directly to the IStream methods with the same names. The TOcStream versions sometimes perform error checking and throw exceptions, but because they correspond closely to the IStream versions, you can consult the IStream documentation in the OLE.HLP file for supplementary information.

Public Constructors and Destructors

TOcStream

~TOcStream

Public Member Functions

Commit

CopyTo

LockRegion

Read

Revert

Seek

SetSize

Stat

UnlockRegion

Write


TOcStream Public Constructors and Destructor

See also	TOcStream

Syntax 1

TOcStream(TOcStorage& storage, const char far* name, bool create, uint32 mode = STGM_READWRITE);

Description

Constructs a new stream object inside the given storage object. name is the name of the stream (analogous to a file name). create determines what happens if a stream called name does not exist. If create is true, the constructor creates the stream. If create is false, the constructor throws the TXObjComp::xStreamOpenError exception. mode is a combination of STGM_xxxx flags (storage mode flags).

(Internally, the constructor parameters are passed to the storage.OpenStream or storage.CreateStream method.)

Syntax 2

TOcStream(TOcStream& stream);

Description

Creates a new stream object by copying stream. (Internally the constructor calls stream.Clone.)

Syntax 3

TOcStream(IStream* stream);

Description

Constructs a TOcStream given an existing IStream interface pointer. Does not add a reference count to the pointer.

Destructor

~TOcStream();

Description

Releases the stream object.


TOcStream::Commit

See also	TOcStream

Syntax

HRESULT Commit(uint32 commitFlags);

Description

Commits any changes made to the storage object containing the stream.

commitFlags controls how the changes are committed. It contains flags from the STGC enum.

Currently this command has no effect because OLE does not support transacted mode for stream objects.


TOcStream::CopyTo

See also	TOcStream

Syntax

HRESULT CopyTo(TOcStream& stream, uint64 cb, uint64 far* read = 0, uint64 far* written = 0);

Description

Copies data to another stream. The copy operation begins from the current file pointer and writes to the pointer position in stream. cb is the number of bytes to copy. read is the number of bytes read from the source stream, and written is the number of bytes written to the destination.


TOcStream::GetIStream

TOcStream

Syntax

IStream* GetIStream();

Description

Returns a pointer to the object's IStream interface without adding a reference count. This pointer can be returned in response to QueryInterface.


TOcStream::LockRegion

See also	TOcStream

Syntax

HRESULT LockRegion(uint64 offset, uint64 cb, uint32 lockType);

Description

Locks a range of bytes in the stream, restricting the access other programs are allowed.

Locking is not supported in the current release of OLE, so the LockRegion command currently has no effect.

offset is the file position of the first byte to lock. cb is the number of bytes to lock. lockType determines whether to block all access or only write access. The possible values are LOCK_WRITE, LOCK_EXCLUSIVE, and LOCK_ONLYONCE.


TOcStream::Read

See also	TOcStream

Syntax

HRESULT Read(void HUGE* pv, ulong cb, ulong far* read = 0);

Description

Copies bytes from the stream to the pv buffer. cb is the number of bytes to read. After the command executes, pcbRead points to the number of bytes actually read.

Read alters the position of the seek pointer within the stream. Read fails if the stream object was not constructed with the STGM_READ mode flag.


TOcStream::Revert

See also	TOcStream

Syntax

HRESULT Revert();

Description

Discards all changes since the the last Commit command (or since the stream was opened, if no Commit has occurred.)

Currently this command has no effect because OLE does not support transacted mode for stream objects.


TOcStream::Seek

See also	TOcStream

Syntax

HRESULT Seek(int64 move, uint32 origin = STREAM_SEEK_SET, uint64 far* newPosition = 0);

Description

Moves the seek pointer within the stream. The seek pointer points to the location in the file where the next read or write operation will begin. The Read and Write commands both move the seek pointer, as well.

Seek can offset the pointer from its present position or move it to an absolute position measured from the beginning or the end of the file.

move is a distance measurement within the file. Its interpretation depends on the value of origin.

origin tells whether move measures a distance from the pointer's current position or from one end of the file.

After Seek, newPosition points to the beginning of the stream.

This table shows the possible values of origin.

Constant	Meaning

STREAM_SEEK_SET	Set the pointer forward move bytes from the start of the file.

STREAM_SEEK_CUR	Offset the pointer move bytes from its current position. (move can be negative.)

STREAM_SEEK_END	Offset the pointer move bytes from the end of the file. (move can be negative.)

It is legal to move the pointer past the end of the stream (but not to move it before the start.)

To determine the current position of the pointer, call Seek passing 0 for move and STREAM_SEEK_SET for origin. newPosition then tells the pointer's position measured from the start of the file.


TOcStream::SetSize

See also	TOcStream

Syntax

HRESULT SetSize(uint64 newSize);

Description

Changes the size of the stream. If newSize is bigger than the current size, bytes are added to the end. (The content of the new bytes is undefined.) If newSize is smaller, the stream is truncated.

SetSize does not affect the position of the seek pointer.


TOcStream::Stat

See also	TOcStream

Syntax

HRESULT Stat(STATSTG far* statstg, uint32 statFlag);

Description

Returns information about the open stream. The information includes, for example, the stream's name, its size, and the times it was created, modified, and last used.

statstg points to a STATSTG structure that receives information from Stat.

statFlag controls the level of detail in the information retrieved. It can be either STATFLAG_DEFAULT or STATFLAG_NONAME. Choosing not to receive the name saves an allocation operation.


TOcStream::UnlockRegion

See also	TOcStream

Syntax

HRESULT UnlockRegion(uint64 offset, uint64 cb, uint32 lockType);

Description

Unlocks a range of bytes previously locked with LockRegion.

Locking is not supported in the current release of OLE, so LockRegion and UnlockRegion currently have no effect.

offset is the file position of the first byte to unlock. cb is the number of bytes to unlock. lockType indicates the kind of restriction to remove.

All three parameters must exactly match those set in a previous call to LockRegion. Every call to LockRegion must have a corresponding UnlockRegion.


TOcStream::Write

See also	TOcStream

Syntax

HRESULT Write(void const HUGE* pv, ulong cb, ulong far* written = 0);

Description

Copies bytes from the pv buffer to the stream. cb is the number of bytes to write. After the command executes, written points to the number of bytes actually written.

Write alters the position of the seek pointer within the stream. Write fails if the stream object was not constructed with the STGM_WRITE mode flag.


TOcStorage class

See also	Compound File I/O Classes

Header File

ocf/ocstorag.h

Description

The TOcStorage class encapsulates OLE's IStorage interface. It manages storages in compound files.

A compound file contains storages and streams. Storages are analogous to file directories and streams to files within a directory. Streams hold data. Storages hold streams and other storages.

Storages have names, just as directories do. The name of the root storage in a compound file is also the name of the disk file itself, so the rules for naming the root storage are the same as the rules for naming any file. Names of substorages under the root, however, can be up to 32 characters, including the terminating null. For more information about names, see the topic Storage Naming Conventions in OLE.HLP.

When you create a storage, you can choose to open it in transacted mode (the default) or in direct mode. In direct mode, write operations have immediate effect, just as they do in normal file I/O. Transacted mode stores all changes in temporary buffers until you call the Commit method. Commit makes the changes permanent. This makes it possible to undo recent changes by calling Revert, which simply discards the current change buffers.

Commands that return HRESULT values correspond directly to the IStorage methods with the same names. The TOcStorage versions sometimes perform error checking and throw exceptions, but because in other respects they correspond closely to the IStorage versions, you can consult the IStorage documentation in the OLE.HLP file for more information.

Public Constructors and Destructors

TOcStorage

~TOcStorage

Public Member Functions

Commit

CopyTo

DestroyElement

EnumElements

GetIStorage

IsStorageFile

IsStorageILockBytes

MoveElementTo

RenameElement

Revert

SetClass

SetElementTimes

SetStateBits

SetTimes

Stat

SwitchToFile

Protected Member Functions

AddRef

CreateStorage

CreateStream

OpenStorage

OpenStream

Release

Protected Data Members

StorageI


TOcStorage Public Constructors and Destructor

See also	TOcStorage

Syntax 1

TOcStorage(const char far* fileName, bool create, uint32 mode = STGM_READWRITE|STGM_TRANSACTED);

Description

Constructs a new root storage object.

fileName is the name of the storage (analogous to a directory name). Because it names a root storage, fileName must conform to the operating system's restrictions on file names. If fileName is 0, the constructor creates a temporary storage that is deleted from the disk when the storage object is released.

Syntax 2

TOcStorage(TOcStorage& parent, const char far* name, bool create, uint32 mode = STGM_READWRITE);

Description

Constructs a substorage within another storage (like a subdirectory within a directory).

parent is the name of the parent storage that contains the new substorage.

name is the name of the new substorage. The name can be up to 32 characters, including the terminating null. It cannot contain any of the following characters: ! . : / \.

Syntax 3

TOcStorage (ILockBytes far* lkbyt, bool create, uint32 mode = STGM_READWRITE|STGM_TRANSACTED);

Description

Constructs a new storage based on the given ILockBytes interface. ILockBytes is OLE's interface for low-level media access. The new storage performs all its I/O through lkbyt.

If it fails, the constructor throws the TXObjComp::xStorageILockError exception.

Syntax 4

TOcStorage (IStorage* storage);

Description

Constructs a new TOcStorage object using the given IStorage interface pointer. Adds a reference count to the pointer. The new object implements all its standard OLE methods through the pointer.

Destructor

~TOcStorage();

Description

Releases the storage object.

Remarks

The create and mode parameters are common to most forms of the constructor.

create determines what happens if a storage with the given name does not exist. If create is true, the constructor creates the storage. If create is false, the constructor throws the TXObjComp::xRootStorageOpenError or TXObjComp::xStorageOpenError exception.

mode determines the access modes for the new storage. The possible values are defined as STGM_xxxx flags. The constructors ignore any share mode flags (such as STGM_SHARE_EXCLUSIVE) and determine the sharing mode automatically based on other mode flags.

For root storages, if you specify STGM_READWRITE, the share mode is STGM_SHARE_DENY_WRITE. If you specify STGM_READONLY, the share mode is STGM_SHARE_DENY_NONE.

Substorages and streams are always opened in STGM_SHARE_EXCLUSIVE mode.


TOcStorage::AddRef

See also	TOcStorage

Syntax

ulong AddRef();

Description

Increments the storage object's reference count. ObjectWindows uses this method internally. Unless you are passing the storage object between tasks, you probably won't need to use AddRef yourself.

The return value is the object's new reference count. The OLE specifications indicate that the return value from any AddRef call should be used for diagnostic purposes only, not in shipping code.


TOcStorage::Commit

See also	TOcStorage

Syntax

HRESULT Commit(uint32 commitFlags);

Description

Makes permanent any changes made to the storage object since the last Commit command, or, if Commit was not called, since the storage was opened.

commitFlags controls how the changes are committed. It contains flags from the STGC enum.

If the storage was opened in direct mode, Commit has no effect. The mode is set in the constructor. Also, changes committed to a substorage do not actually become permanent until the parent commits, as well. If the parent reverts, its substorages also revert.


TOcStorage::CopyTo

See also	TOcStorage

Syntax

HRESULT CopyTo(uint32 ciidExclude, IID const far* rgiidExclude, SNB snbExclude, TOcStorage& dest);

Description

Copies one storage to another. The first three parameters allow you to exclude some elements from the copy operation, identifying them either by interface IDs or by the names of stream and substorage elements. All subelements nested within the source, down to any level, are copied as well. Copied elements are added to the existing contents of the destination, overwriting any with the same names.

ciidExclude tells how many items are in the rgiidExclude array. If rgiidExclude is 0, then this parameter is ignored.

rgiidExclude points to an array of interfaces identifiers that the caller takes responsibility for copying. CopyTo leaves them alone. If rgiidExclude is 0, all elements are copied. If rgiidExclude is not 0 but ciidExclude is 0, CopyTo copies only the state of the storage, not its contents.

snbExclude points to a string name block (SNB) naming elements in the storage that should not be copied. An SNB value points to an array of string pointers. The last element in the array is a null pointer. The strings themselves follow contiguously in memory after the null pointer. This parameter is ignored if the rgiidExclude array contains IID_IStorage (the GUID identifier for the IStorage interface).

dest is the TOcStorage object that receives the copied information.


TOcStorage::CreateStorage

See also	TOcStorage

Syntax

HRESULT CreateStorage(const char far* name, uint32 mode, uint32 rsrvd1, uint32 rsrvd2, IStorage far*far* storage);

Description

Creates a new substorage (like creating a subdirectory within a directory).

name points to the name of the new storage.

mode combines STGM xxxx flags to set access modes for the new storage.

rsrvd1 and rsrvd2 are reserved for future use and must be set to 0.

storage is where the command returns the IStorage interface to the newly created object. If creation fails, storage is set to 0.


TOcStorage::CreateStream

See also	TOcStorage

Syntax

HRESULT CreateStream(const char far* name, uint32 mode, uint32 rsrvd1, uint32 rsrvd2, IStream far* far* stream);

Description

Creates a new stream within the storage (like a file within a directory).

name points to the name of the new stream.

mode combines STGM xxxx flags to set access modes for the new stream.

rsrvd1 and rsrvd2 are reserved for future use and must be set to 0.

stream is where the command returns the IStream interface to the newly created object. If creation fails, stream is set to 0.


TOcStorage::DestroyElement

See also	TOcStorage

Syntax

HRESULT DestroyElement(const char far* name);

Description

Deletes an element (a storage or a stream) from within the storage. name is the identifier assigned to the element when it was created. If the storage uses transacted mode, this command can be undone using Revert.


TOcStorage::EnumElements

See also	TOcStorage

Syntax

HRESULT EnumElements(uint32 reserved1, void far* reserved2, uint32 reserved3, IEnumSTATSTG far*far* ppenm);

Description

Returns an enumerator object whose methods can list all the elements (storages and streams) within the storage. The first three parameters are reserved and must be 0. ppenm is where the command returns the IEnumSTATSTG interface to the newly created enumeration object.

For information on the IEnumSTATSTG interface, see OLE.HLP.


TOcStorage::GetIStorage

TOcStorage

Syntax

IStorage* GetIStorage();

Description

Returns a pointer to the object's IStorage interface without adding a reference count. This pointer can be returned in response to QueryInterface.


TOcStorage::IsStorageFile

See also	TOcStorage

Syntax

static HRESULT IsStorageFile(const char far* pwcsName);

Description

Determines whether the file named pwcsName contains an IStorage object. If the file contains a storage object, the function returns S_OK. If it does not, the function returns S_FALSE.


TOcStorage::IsStorageILockBytes

See also	TOcStorage

Syntax

static HRESULT IsStorageILockBytes(ILockBytes far* plkbyt);

Description

Determines whether the plkbyt byte array object contains an IStorage object. If the lockbytes object contains a storage, the function returns S_OK. If it does not, it returns S_FALSE.


TOcStorage::MoveElementTo

See also	TOcStorage

Syntax

HRESULT MoveElementTo(char const far* name, TOcStorage& dest, char const far* newName, uint32 grfFlags);

Description

Moves an element from one storage to another (like moving files from one directory to another).

name identifies the element to be moved.

dest is the TOcStorage object where the element will be placed.

newName is the element's new identifier.

grfFlags determines whether the original element is deleted after being copied to dest. The possible values are STGMOVE_MOVE and STGMOVE_COPY.


TOcStorage::OpenStorage

See also	TOcStorage

Syntax

HRESULT OpenStorage(const char far* name, IStorage far* stgPriority, uint32 mode, SNB snbExclude, uint32 rsrvd, IStorage far*far* storage);

Description

Opens an existing substorage object within the storage.

name identifies the storage to open.

stgPriority is usually 0. If you have already opened the name storage element, passing the original IStorage pointer causes OpenStorage to close and reopen the storage using the new mode access flags.

mode combines STGM_xxxx flags to indicate the access modes for the new storage object.

snbExclude points to an array of elements within the substorage that will be emptied (but not destroyed) when the storage is opened. This parameter is usually used together with stgPriority.

rsrvd is reserved and must be 0.

storage is where the command returns a pointer to the newly opened storage object's IStorage interface. If the command fails, storage is 0.

For more information about the priority and exclusion parameters, see the description of StgOpenStorage in OLE.HLP.


TOcStorage::OpenStream

See also	TOcStorage

Syntax

HRESULT OpenStream(const char far* name, void far *rsrvd1, uint32 grfMode, uint32 rsrvd2, IStream far *far *stream);

Description

Opens an existing stream object within the storage.

name identifies the stream to open.

rsrvd1 and rsrvd2 are reserved and must be 0.

grfMode combines STGM_xxxx flags to indicate the access modes for the new stream object.

stream is where the command returns a pointer to the newly opened storage object's IStream interface. If the command fails, stream is 0.


TOcStorage::Release

See also	TOcStorage

Syntax

ulong Release()

Description

Decrements the object's reference count. ObjectWindows uses this method internally. Unless you are passing the storage object between tasks, you probably won't need to use Release yourself.

The return value is the object's new reference count. When it reaches 0, the object destroys itself. The OLE specifications indicate that the return value from any Release call should be used for diagnostic purposes only, not in shipping code.


TOcStorage::RenameElement

See also	TOcStorage

Syntax

HRESULT RenameElement(const char far* oldName, const char far* newName);

Description

Changes the identifier assigned to a stream or substorage within the storage.

oldName identifies the element whose name you want to change.

newName is the new identifier to give the element.


TOcStorage::Revert

See also	TOcStorage

Syntax

HRESULT Revert();

Description

Revokes any changes made to a storage, or to any elements it contains, since the last Commit command. If Commit was not called, the storage reverts to the state it was in when opened.


TOcStorage::SetClass

See also	TOcStorage

Syntax

HRESULT SetClass(const IID far& clsid);

Description

Assigns clsid as the globally unique identifier (GUID) for the storage. The intitial GUID for any new storage is CLSID_NULL. Call Stat to determine the storage's current class ID. The class ID is a persistent attribute.


TOcStorage::SetElementTimes

See also	TOcStorage

Syntax

HRESULT SetElementTimes(const char far* name, FILETIME const far* pctime, FILETIME const far* patime, FILETIME const far* pmtime);

Description

Compound files can record the times of creation, last modification, and last access for each element within the file. This command sets these values explicitly for any element. Time values are expressed as FILETIME structures. To determine the values already set for these times, call Stat.

name identifies the element whose time attributes you want to modify.

pctime points to a structure containing the new creation time.

patime points to a structure containing the new time to show for last access to the file.

pmtime points to a structure containing the new time to show for last modification to the file.

Leave any of the FILETIME parameters 0 to avoid changing the existing value.

Not all implementations of compound files support all three times for all elements. The attributes of a root storage, for example, depend on the underlying file system. Microsoft's OLE implementation does not support any time stamps for internal streams. If you attempt to assign values for unsupported attributes, the values are ignored.


TOcStorage::SetStateBits

See also	TOcStorage

Syntax

HRESULT SetStateBits(uint32 grfStateBits, uint32 grfMask);

Description

Stores information about the current state of the storage as bits in a 32-bit value. When first created, a storage's state is 0. Currently no state bits are defined, but all 32 are reserved for system use and applications should not use them privately.


TOcStorage::SetTimes

See also	TOcStorage

Syntax

static HRESULT SetTimes(char const far* name, FILETIME const far* pctime, FILETIME const far* patime, FILETIME const far* pmtime);

Description

Sets the times of creation, last modification, and last access for a disk file. Time values are expressed as FILETIME structures.

name identifies the file whose time attributes you want to modify.

pctime points to a structure containing the new creation time.

patime points to a structure containing the new time to show for last access to the file.

pmtime points to a structure containing the new time to show for last modification to the file.

To avoid changing an existing value, set the corresponding FILETIME parameter to 0.

The underlying operating system determines whether all three of the time attributes are supported. If you attempt to assign values for unsupported attributes, the values are simply ignored.


TOcStorage::Stat

See also	TOcStorage

Syntax

HRESULT Stat(STATSTG far *pstatstg, uint32 statFlag);

Description

Returns information about the storage. The information includes, for example, the storage's name, its size, and the times it was created, modified, and last used.

pstatstg points to a STATSTG structure that receives information from Stat.

statFlag controls the level of detail in the information retrieved. It can be either STATFLAG_DEFAULT or STATFLAG_NONAME. Choosing not to receive the name saves an allocation operation.


TOcStorage::SwitchToFile

See also	TOcStorage

Syntax

HRESULT SwitchToFile(const char far* newPath);

Description

Copies an entire compound file to a new disk file and associates the storage with the new disk file. newPath names the destination file. SwitchToFile fails if the storage object is not a root storage (supporting the IRootStorage interface).


TOcStorage::StorageI

Syntax

IStorage* StorageI;

Description

[Insert description.]


FILETIME struct

See also

Header File

ocf/ocstorag.h

Description

This structure holds a 64-bit value that indicates a date and time. One field holds the low half of the value and the other holds the high half. The complete value represents the number of 100-nanosecond intervals since January 1, 1601.

OLE uses the FILETIME structure to record the creation and access times for file elements.

To manipulate FILETIME values, call any of the following OLE commands (described in OLE.HLP): CoDosDateTimeToFileTime, CoFileTimeToDosDateTime, and CoFileTimeNow.

Public Data Members

dwLowDateTime

dwHighDateTime


FILETIME::dwLowDateTime

FILETIME

Syntax

uint32 dwLowDateTime;

Description

Contains the low-order half of a 64-bit time counter value.


FILETIME::dwHighDateTime

FILETIME

Syntax

uint32 dwHighDateTime;

Description

Contains the high-order half of a 64-bit time counter value.


STATSTG Struct

See also	Compound File I/O Enumerated Types and Structs

Header File

ocf/ocstorag.h

Description

This structure holds information describing a stream or storage object (one that supports the IStream or IStorage interface.) The information includes, for example, the size of the file element, its creation and access times, its operating modes, and its identifiers.

Public Data Members

atime

cbSize

clsid

ctime

grfLocksSupported

grfMode

grfStateBits

mtime

pwcsName

reserved

type


STATSTG::atime

See also	STATSTG

Syntax

FILETIME atime;

Description

atime stores the time when the last access operation was performed on the file element. It is defined for storages only. Streams do not have time stamps.


STATSTG::cbSize

STATSTG

Syntax

ULARGE_INTEGER cbSize;

Description

cbSize stores the number of bytes in a stream (or a lockbytes array). For storages, this value is not defined.


STATSTG::clsid

See also	STATSTG

Syntax

IID clsid;

Description

Holds a globally unique identifier (GUID) assigned as the clsid of a storage object. The clsid of any newly created storage is CLSID_NULL. Streams do not have class identifiers.


STATSTG::ctime

See also	STATSTG

Syntax

FILETIME ctime;

Description

ctime stores the time when the file element was created. It is defined for storages only. Streams do not have time stamps.


STATSTG::grfLocksSupported

See also	STATSTG

Syntax

uint32 grfLocksSupported;

Description

Contains bit flags indicating whether a stream or lockbyte object supports particular kinds of locks. The possible flags are LOCK_WRITE, LOCK_EXCLUSIVE, and LOCK_ONLYONCE. They can be combined with the bitwise OR operator.

The value of grfLocksSupported is undefined for storage objects because they do not support locks at all.


STATSTG::grfMode

See also	STATSTG

Syntax

uint32 grfMode;

Description

Contains bit flags indicating the access mode in which the file element was opened. The possible values are STGM_xxxx flags.


STATSTG::grfStateBits

See also	STATSTG

Syntax

uint32 grfStateBits;

Description

Holds information about the current state of a storage. When first created, a storage's state is 0. Currently no state bits are defined, but all 32 are reserved for system use and applications should not use them privately.


STATSTG::mtime

See also	STATSTG

Syntax

FILETIME mtime;

Description

mtime stores the time when the file element was last modified. It is defined for storages only. Streams do not have time stamps.


STATSTG::pwcsName

See also	STATSTG

Syntax

char far* pwcsName;

Description

Points to the name assigned at creation to identify the file element. The Stat function allocates space for this string, but the caller is responsible for freeing it.


STATSTG::reserved

STATSTG

Syntax

uint32 reserved;

Description

This field is reserved and should be ignored.


STATSTG::type

STATSTG

Syntax

uint32 type;

Description

The value in this field indicates the type of object the STATSTG structure describes. The possible values are STGTY_STORAGE, STGTY_STREAM, and STGTY_LOCKBYTES.


STGC enum

See also	Compound File I/O Enumerated Types and Structs

Header File

ocf/ocstorag.h

Description

These flags are used in Commit commands for compound files to control how changes are committed. They are bit values and can be combined with the bitwise OR operator (|).

Constant	Meaning

STGC_DEFAULT 	Commits changes normally.

STGC_OVERWRITE	Allows new data to overwrite old data. Without this flag, Commit writes to a new area and erases the old data only after the Write operation succeeds.

STGC_ONLYIFCURRENT	Commits changes only if doing so does not overwrite changes already made by another process.

STGC_DANGEROUSLYCOMMIT-

MERELYTODISKCACHE	Commits changes without flushing the disk caching buffer. Sacrifices security for speed.

For general use, STGC_ONLYIFCURRENT is recommended; STGC_OVERWRITE is not.


STGMxxxx Constants

See also

Header File

ocf/ocstorag.h

Description

These constants specify access modes for file elements: streams, storages, and lockbyte arrays. The constants are bit flags and can be combined with the bitwise OR operator (|).

Constant	Meaning

STGM_DIRECT	Uses direct access mode (commits each change immediately)

STGM_TRANSACTED	Uses transacted mode (buffers changes until committed explicitly)

STGM_READ	Allows read operations

STGM_WRITE	Allows write operations

STGM_READWRITE	Allows read and write operations

STGM_SHARE_EXCLUSIVE	Denies all access to other tasks

STGM_SHARE_DENY_WRITE	Denies write access to other tasks

STGM_SHARE_DENY_READ	Denies read access to other tasks

STGM_SHARE_DENY_NONE	Allows all access to other tasks

STGM_CREATE	Creates the file element if it does not already exsit

STGM_CONVERT	If the a file element with the given name already exists, copies its contents to a stream called CONTENTS and creates a new element with the given name

STGM_PRIORITY	Gives the opener exclusive access to the committed version of the file to reduce the cost of a subsequent copy operation

STGM_DELETEONRELEASE	Deletes the file element from the disk as soon as its reference count reaches 0

For more information about each option, see OLE.HLP.


TOcFormat class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

Holds information about one Clipboard format that a particular view supports.

TOcFormat, TOcFormatList, and TOcFormatListIter all work together to manage a list of formats. TOcFormatList adds and deletes TOcFormat objects from the list. TOcFormatListIter enumerates the items in the list whenever the view needs to examine them one by one. Because TOcView creates and maintains this list internally, you do not need to use these classes directly.

When ObjectComponents receives your document registration table, it sees entries for each Clipboard format that the document receives or produces. From these entries, TOcView creates a list of objects of type TOcFormat, each object representing one format. The view needs this list to know when a Clipboard command or drag and drop operation can succeed. For example, if the user drags a bitmap object over a view that accepts only text, TOcView refuses the object and the server adjusts the cursor accordingly.

Public Constructors

TOcFormat

Public Member Functions

operator =

operator ==

Disable

GetAspect

GetDirection

GetFormatId

GetFormatInfo

GetFormatName

GetMedium

GetRegName

IsDisabled

SetAspect

SetDirection

SetFormatId

SetFormatName

SetFormatName

SetLinkable

SetMedium


See Also

ObjectComponents Header Files

TOcFormatList

TOcFormatListIter

TOcView


TOcFormat::TOcFormat

Sea Also	TOcFormat

Syntax 1

TOcFormat();

Description

Creates an empty TOcFormat object (default constructor).

Syntax 2

TOcFormat(uint fmtId, char far* fmtName, char far* fmtResultName, uint fmtMedium, bool fmtIsLinkable, uint aspect = 1, uint direction = 1);

Description

Creates a TOcFormat object and initializes it with information about a particular Clipboard format.

fmtId is a number (such as CF_TEXT or CF_SYLK) identifying a particular Clipboard format.

fmtName is the name string identifying a Clipboard format.

fmtResultName is a string that describes this format to the user. For standard Clipboard formats, this string comes from the OLEVIEW.RC file. For user-defined formats, it comes from the string supplied in the TOcApp::AddUserFormatName.

fmtMedium is one of the ocrxxxx medium constants specifying the channel the application uses for transferring data in this format (for example, global handle or disk file).

fmtIsLinkable is true if the application allows containers to link to data in this format and false if it does not.

aspect combines bit flags to specify the presentation aspects the application supports for the data format. The flags are defined as ocrxxxx aspect constants.

direction indicates whether the application can both give and receive data in the given format. Possible values are defined as ocrxxxx direction constants.


See Also

ocrxxxx aspect Constants

ocrxxxx Clipboard Constants

ocrxxxx Direction Constants

ocrxxxx Medium Constants


TOcFormat::operator =

TOcFormat

Syntax

void operator = (const TOcFormatInfo& formatInfo);

Description

Takes information from the formatInfo parameter and reinitializes the TOcFormat object.


TOcFormat::operator ==

TOcFormat

Syntax

bool operator ==(const TOcFormat& other);

Description

Returns true if &other is the same as this.


TOcFormat::Disable

TOcFormat

Syntax

void Disable(bool disable = true);

Description

Marks the format as available or unavailable. Disabling a format in effect removes it temporarily from the view's list. Set disable to true if you decide not to let the view work with a particular data format.


TOcFormat::GetAspect

See Also	TOcFormat

Syntax

uint GetAspect() const;

Description

Returns a bit flag mask indicating the presentation aspects that the view supports for the data format. The bit flags are defined as ocrxxxx aspect constants.


See Also

ocrxxxx Aspect Constants

TOcFormat::SetAspect


TOcFormat::GetDirection

See Also	TOcFormat

Syntax

uint GetDirection() const;

Description

Returns a value indicating whether the view can both give and receive data in the format. Possible values are defined as ocrxxxx direction constants.


See Also

ocrxxxx Direction Constants

TOcFormat::SetDirection


TOcFormat::GetFormatId

See Also	TOcFormat

Syntax

uint GetFormatId() const;

Description

Returns the number that identifies the data format for the operating system. For standard formats, the number is a constant such as CF_TEXT or CF_BITMAP. For custom formats, it is the ID returned from RegisterClipboardFormat.


See Also

ocrxxxx Clipboard Constants

TOcFormat::SetFormatId


TOcFormat::GetFormatInfo

See Also	TOcFormat

Syntax

void GetFormatInfo(TOcFormatInfo far& formatInfo);

Description

Fills the formatInfo structure with information about the data format.


See Also

TOcFormat::operator =

TOcFormatInfo


TOcFormat::GetFormatName

See Also	TOcFormat

Syntax

char far* GetFormatName();

Description

Returns the string that names the data format. This is the name that appears in the list box of the Paste Special dialog box.

The strings associated with standard formats ("Bitmap", "DIF") are defined in OLEVIEW.RC. The strings associated with custom formats come from TOcApp::AddUserFormatName.


See Also

TOcApp::AddUserFormatName

TOcFormat::SetFormatName


TOcFormat::GetMedium

See Also	TOcFormat

Syntax

uint GetMedium() const;

Description

Returns a number indicating the channel the application uses for transferring data in this format (for example, global handle or disk file). Possible values are defined as ocrxxxx medium constants.


See Also

ocrxxxx Medium Constants

TOcFormat::SetMedium


TOcFormat::GetRegName

TOcFormat

Syntax

char far* GetRegName();

Description

Returns the registered name of the format.


TOcFormat::IsDisabled

See Also	TOcFormat

Syntax

bool IsDisabled() const;

Description

Returns true if the format is currently disabled. A view disables formats if for any reason the view decides not to support the format after all. Disabling a format signals that the view no longer sends or receives data in that format. To reenable the format, call Disable.


See Also

TOcFormat::Disable


TOcFormat::SetAspect

See Also	TOcFormat

Syntax

void SetAspect(uint aspect);

Description

aspect is a bit flag mask indicating the presentation aspects that the view supports for the data format. The bit flags are defined as ocrxxxx aspect constants.


See Also

ocrxxxx Aspect Constants

TOcFormat::GetAspect


TOcFormat::SetDirection

See Also	TOcFormat

Syntax

void SetDirection(uint direction);

Description

direction indicates whether the view can both give and receive data in the format. Possible values for direction are defined as ocrxxxx direction constants.


See Also

ocrxxxx Direction Constants

TOcFormat::GetDirection


TOcFormat::SetFormatId

See Also	TOcFormat

Syntax

void SetFormatId(uint id);

Description

is identifies the data format for the operating system. For standard formats, id is a constant such as CF_TEXT or CF_BITMAP. For custom formats, it is the number returned by RegisterClipboardFormat.


SeeAlso

ocrxxxx Clipboard Constants

TOcFormat::GetFormatId

TClipboard::RegisterClipboardFormat (OWL.HLP)


TOcFormat::SetFormatName

See Also	TOcFormat

Syntax

Form 1

void SetFormatName(uint id, TOcApp& ocApp);

Form 2

void SetFormatName(char far* name, TOcApp& ocApp);

Description

Both forms of SetFormatName retrieve from the format list in TOcApp two strings to describe a particular data format: the user-registered name and the format result string. The retrieved strings are stored internally. Form 1 identifies the format by its ID and Form 2 identifies the format by its Windows-registered name.

The TOcApp object keeps a list of all the Clipboard formats the application knows about. Each TOcView keeps a separate list of the Clipboard formats it supports. SetFormatName updates strings for individual views from the central application list.

The Windows-registered name is the one passed to RegisterClipboardFormat. For standard Clipboard formats, the name comes from OLEVIEW.RC. The user-registered name can differ from the Windows-registered name for user-defined formats if you have called TOcApp::AddUserFormatName. The user-registered name is the one displayed in Clipboard dialog boxes.

The result string is a longer string describing the format to the user.


See Also

TClipboard::RegisterClipboardFormat (OWL.HLP)

TOcApp::AddUserFormatName

TOcFormat::GetFormatName


TOcFormat::SetLinkable

TOcFormat

Syntax

void SetLinkable(bool link = true);

Description

Specifies whether data in this format can be the source for a linked object.


TOcFormat::SetMedium

See Also	TOcFormat

Syntax

void SetMedium(uint medium);

Description

Sets the transfer mechanism that an application uses for transferring data in this format (for example, global handle or disk file). Possible values for medium are defined as ocrxxxx medium constants.


See Also

ocrxxxx Medium Constants

TOcFormat::GetMedium


TOcFormatList class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

Manages a list of Clipboard formats that a particular view supports.

TOcFormat, TOcFormatList, and TOcFormatListIter all work together to maintain the list of formats. TOcFormatList adds and deletes TOcFormat objects from the list. TOcFormatListIter enumerates the items in the list whenever the view needs to examine them one by one. Because TOcView creates and maintains this list internally, it is usually not necessary for you to use any of these classes directly.

When ObjectComponents receives your document registration table, it sees entries for each Clipboard format that the document receives or produces. From these entries, TOcView creates a list of objects of type TOcFormat, each object representing one format. The view needs this list to know when a Clipboard command or drag and drop operation can succeed. For example, if the user drags a bitmap over a view that accepts only text, TOcView knows the object cannot be dropped and adjusts the cursor accordingly.

Public Constructor and Destructor

TOcFormatList

~TOcFormatList

Public Member Functions

operator []

Add

Clear

Count

Detach

Find

IsEmpty


See Also

ObjectComponents Header Files

TOcFormat

TOcFormatListIter

TOcView


TOcFormatList::TOcFormatList

See Also	TOcFormatList

Constructor

TOcFormatList();

Description

Creates an empty list object. To insert items in the list, call the Add method.

Destructor

~TOcFormatList();

Description

Deletes all the items in the list.


See Also

TOcFormatList::Add


TOcFormatList::operator []

TOcFormatList

Syntax

TOcFormat*& operator [](unsigned index);

Description

Retrieves a Clipboard format by its position in the list. If index is 1, for example, the [] returns the second item in the list. The order of items depends on the priority assigned to them when they are registered.


TOcFormatList::Add

See Also	TOcFormatList

Syntax

int Add(TOcFormat* format);

Description

Inserts a new Clipboard format item in the list. Returns 0 for failure and 1 for success.


See Also

TOcFormatList::Clear


TOcFormatList::Clear

See Also	TOcFormatList

Syntax

void Clear(int del = 1);

Description

Removes all the items from the list. If del is 1, Clear also deletes all the TOcFormat objects.


See Also

TOcFormatList::Add

TOcFormatList::Detach


TOcFormatList::Count

See Also	TOcFormatList

Syntax

virtual uint Count() const;

Description

Returns the number of items in the list.


See Also

TOcFormatList::IsEmpty


TOcFormatList::Detach

See Also	TOcFormatList

Syntax

int Detach(const TOcFormat* format, int del = 0);

Description

Removes one format item from the list. If del is 1, then Detach also deletes the TOcFormat object.


See Also

TOcFormatList::Add

TOcFormatList::Clear


TOcFormatList::Find

TOcFormatList

Syntax 1

unsigned Find(const TOcFormat* format) const;

Description

Find searches the list for the object passed as format. If the object is found, then Find returns the object's position in the list. (The first position is 0.) If the object is not in the list, Find returns UINT_MAX.

Syntax 2

unsigned Find(uint const id) const;

Description

Find searches the list for the object passed as id. If the object is found, then Find returns the object's position in the list. (The first position is 0.) If the object is not in the list, Find returns UINT_MAX.


TOcFormatList::IsEmpty

See Also	TOcFormatList

Syntax

int IsEmpty() const;

Description

Returns 1 if the list object currently contains no TOcFormat items and 0 if the list is not empty.


See Also

TOcFormatList::Count


TOcFormatListIter class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

Enumerates all the Clipboard formats that a particular view supports.

TOcFormat, TOcFormatList, and TOcFormatListIter all work together to manage the list of formats. TOcFormatList adds and deletes TOcFormat objects from the list. TOcFormatListIter enumerates the items in the list whenever the view needs to examine them one by one. Because TOcView creates and maintains this list internally, it is usually not necessary for you to use any of these classes directly.

When ObjectComponents receives your document registration table, it sees entries for each Clipboard format that the document receives or produces. From these entries, TOcView creates a list of objects of type TOcFormat, each object representing one format. The view needs this list to know when a Clipboard command or drag and drop operation can succeed. For example, if the user drags a bitmap object over a view that accepts only text, TOcView knows the object cannot be dropped and adjusts the cursor accordingly.

Public Constructor

TOcFormatListIter

Public Member Functions

operator ++

operator ++

Current

operator int

Restart


See Also

ObjectComponents Header Files

TOcFormat

TOcFormatList

TOcView


TOcFormatListIter::TOcFormatListIter

TOcFormatListIter

Syntax

TOcFormatListIter(const TOcFormatList& collection)

Description

Constructs an iterator to enumerate the Clipboard formats contained in collection.


TOcFormatListIter::operator ++

TOcFormatListIter

Syntax 1

TOcFormat* operator++();

Description

Returns the current format and then advances the iterator to point to the next format (post-increment).

Syntax 2

TOcFormat* operator++(int);

Description

Advances the iterator to point to the next format in the list and then returns that format (pre-increment).


TOcFormatListIter::Current

TOcFormatListIter

Syntax

TOcFormat* Current() const;

Description

Returns the format that the iterator currently points to.


TOcFormatListIter::operator int

TOcFormatListIter

Syntax

operator int() const;

Description

Converts the iterator to an integer value in order to test whether the iterator has finished enumerating the collection. If parts remain unenumerated, the operator returns the iterator's current position in the list of parts. If the iterator has reached the end of the list, the operator returns zero.


TOcFormatListIter::Restart

TOcFormatListIter

Syntax 1

void Restart();

Description

Resets the iterator to begin again with the first format in the list.

Syntax 2

void Restart(unsigned start, unsigned stop);

Description

Resets the iterator to enumerate a subset of the format list, beginning with the object at position start and ending with the object at position stop.


TOcView class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Base Class

TUnknown

Description

TOcView manages the presentation of a container's compound document containing linked and embedded objects. Each object in the document is represented by an object of type TOcPart. The document view knows which parts are selected or activated. It scrolls the window and remembers which parts are visible. It transfers parts to and from the document through the Clipboard or through drag-and-drop operations.

Every TOcView has a corresponding TOcDocument. The ObjectComponents document object implements the OLE interfaces that manipulate the data in a compound document. TOcView implements the interfaces that manipulate the appearance of a compound document.

TOcView is a COM object and implements the IUnknown interface.

Public Constructor

TOcView

Public Member Functions

ActivatePart

BrowseClipboard

BrowseLinks

Copy

EvActivate

EvClose

EvResize

EvSetFocus

GetActivePart

GetDocLink

GetOcData

GetOcDocument

GetOrigin

GetWindowRect

IsOptionSet

InvalidatePart

Paste

PasteNative

RegisterClipFormats

ReleaseObject

Rename

ScrollWindow

SetOcData

SetOption

SetLink

SetupWindow

Protected Destructor

~TOcView();

Protected Member Functions

ForwardEvent

Init

Shutdown

Protected Data Members

ActivePart

ContainerHost

Extent

FormatList

Link

OcApp

OcData

OcDocument

Options

OrgTitle

Origin

RegList

ServerHost

WinTitle


See Also

ObjectComponents Header Files

TOcApp

TOcDocument

TOcPart

TUnknown


TOcView::TOcView

See Also	TOcView

Syntax

TOcView(TOcDocument& doc, TOcContainerHost* ch, TOcServerHost* sh, TRegList* regList = 0, IUnknown* outer=0);

Description

doc refers to the TOcDocument object that corresponds to the view. TOcDocument manages the data in a compound document, and TOcView manages the appearance of the document on the screen.

regList is the registration structure for a particular document. Use the BEGIN_REGISTRATION and END_REGISTRATION macros to create an object of type TRegList.

ch is the hosting application’s container object.

sh is the hosting application’s server object.

outer is the root interface of an outer object inside which the new view is asked to aggregate itself.


See Also

Registration Macros (OWL.HLP)

TAutoObject

TOcDocument


TOcView::~TOcView

TOcView

Syntax

~TOcView();

Description

Destroys the view object.


TOcView::ActivatePart

See Also	TOcView

Syntax

bool ActivatePart(TOcPart* part);

Description

Attempts to activate the given part (by calling TOcPart::Activate). Returns true if the designated part becomes active and false otherwise. If any other part was already active, it is deactivated first.


See Also

TOcPart::Activate

TOcView::ActivePart

TOcView::GetActivePart


TOcView::BrowseClipboard

See Also	TOcView

Syntax

bool BrowseClipboard(TOcInitInfo& initInfo);

Description

Displays the Paste Special dialog box showing the available formats for the data currently on the Clipboard, allowing the user to choose what format to paste. Returns true if the user pastes data and false if the user cancels or the dialog box fails.

Create initInfo first by passing the view to the TOcInitInfo constructor. BrowseClipboard fills initInfo with information about the object. Then use initInfo to create a new TOcPart.

This function calls TOcApp::BrowseClipboard.


See Also

TOcApp::BrowseClipboard

TOcInitInfo

TOcPart


TOcView::BrowseLinks

See Also	TOcView

Syntax

bool BrowseLinks();

Description

Displays the Links dialog box showing all the linked objects in the compound document and what they are linked to. The user can modify the displayed links, perhaps to reconnect with a file that was moved. Returns false if an error prevents the dialog box from being displayed or if the user cancels the dialog box.


See Also

TOcApp::BrowseClipboard


TOcView::Copy

TOcView

Syntax

bool Copy(TOcPart* part);

Description

Creates a copy of a linked or embedded object and places it on the Clipboard. Returns true if the operation succeeds. Call Copy in response to Cut or Copy commands from the Edit menu.


TOcView::EvActivate

See Also	TOcView

Syntax

void EvActivate(bool activate);

Description

A container calls this function if any of its windows gains focus while any of its linked or embedded objects is being edited in place. EvActivate restores focus to the in-place activated view. If the user clicks in the client window of an MDI frame, for example, the client window needs to shift the focus back to the view, which in turn restores focus to the activated part. A part engaged in in-place editing should always retain the focus.

activate should be true if the window is gaining focus and false if it is losing it.


See Also

TOcView::EvClose

TOcView::EvResize

TOcView::EvSetFocus


TOcView::EvClose

See Also	TOcView

Syntax

virtual void EvClose();

Description

A container calls this function to tell ObjectComponents that the window associated with the view has closed.


See Also

TOcView::EvActivate

TOcView::EvResize

TOcView::EvSetFocus


TOcView::EvResize

See Also	TOcView

Syntax

void EvResize();

Description

A container calls this function to tell OLE when the window associated with the view changes size. OLE might need this information to let a server modify its tool bar during in-place editing.


See Also

TOcView::EvActivate

TOcView::EvClose

TOcView::EvSetFocus


TOcView::EvSetFocus

See Also	TOcView

Syntax

bool EvSetFocus(bool set);

Description

A container calls this function to tell OLE that the window associated with the view has either received or lost the input focus. Make set true if the window gained the focus or false if it lost the focus.

The function returns false if the view is unable to receive the focus. That happens if an object in the view is engaged in in-place editing. Such objects retain the focus until the editing session ends.


See Also

TOcView::EvActivate

TOcView::EvResize

TOcView::EvSetFocus


TOcView::GetActivePart

See Also	TOcView

Syntax

TOcPart* GetActivePart();

Description

Returns the currently active part. If the view does not contain an active part, the return value is 0.


See Also

TOcView::ActivePart

TOcView::ActivatePart


TOcView::GetDocLink

See Also 	TOcView

Syntax

TOcLinkView* GetDocLink(const char far* name = 0)

Description

Returns the associated TOcLinkView object.


See Also

TOcLinkView


TOcView::GetOcData

See Also 	TOcView

Syntax

TOcDataProvider* GetOcData();

Description

Returns the associated TOcDataProvider object.


See Also

TOcDataProvider


TOcView::GetOcDocument

See Also	TOcView

Syntax

TOcDocument& GetOcDocument();

Description

Returns the ObjectComponents document associated with the view. Views and documents work in pairs. TOcView manages the appearance of a compound document and TOcDocument manages the data in it.


See Also

TOcDocument

TOcView::OcDocument


TOcView::GetOrigin

See Also	TOcView

Syntax

TPoint GetOrigin() const;

Description

Returns the physical coordinates currently mapped to the upper left corner of the container window's client area. ObjectWindows programmers can ignore this method because TOleWindow performs scrolling for you.


See Also

TOcView::Origin

TOcView::ScrollWindow

TOleWindow (OWL.HLP)

TPoint (OWL.HLP)


TOcView::GetWindowRect

See Also	TOcView

Syntax

TRect GetWindowRect() const;

Description

Returns the client rectangle for the view window.


See Also

TOcView::GetOrigin

TRect (OWL.HLP)


TOcView::InvalidatePart

TOcView

Syntax

void InvalidatePart(TOcPartChangeInfo& changeInfo);

Description

Sends an OC_VIEWPARTINVALID message to the container window. If the container window responds with false to indicate it has not processed the message, InvalidatePart tells the system that the area inside the part's bounding rectangle is invalid and needs repainting.


TOcView::IsOptionSet

Syntax

bool IsOptionSet(uint 32 option) const;

Description

Returns a Boolean value indicating whether option is set for this view.


TOcView::Paste

TOcView

Syntax

bool Paste(bool linking = false);

Description

Inserts an object from the Clipboard into the compound document. If linking is true, Paste will try to create a link rather than embedding the new object. Make linking true when processing the Paste Link command.


TOcView::PasteNative

SeeAlso	TOcView

Syntax

bool PasteNative(TOcInitInfo& init, TPoint far* where = 0);

Description

If the Clipboard data corresponds to one of the view’s native data formats (that is, if the Find function returns true for the data format in init), the PasteNative function creates a TOcFormatData object for the Clipboard data and then calls the EvOcViewClipData function of the view’s ServerHost object. Finally, the PastNative function calls the ReleaseDataObject function of the init object.


See Also

TOcFormatData

TOcServerHost::EvOcViewClipData

TOcInitInfo::ReleaseDataObject


TOcView::RegisterClipFormats

See Also	TOcView

Syntax

bool RegisterClipFormats(TRegList& regList);

Description

Tells OLE what Clipboard formats the document understands. The list of formats comes from regList, the document's registration structure. Use the BEGIN_REGISTRATION and END_REGISTRATION to create regList. Also, the REGFORMAT places Clipboard format entries in the structure. To register custom Clipboard formats, be sure to call TOcApp::AddUserFormatName as well. For more information, see Registration Macros in OWL.HLP.

RegisterClipFormats is called automatically when the view is constructed.


See Also

Registration Macros (OWL.HLP)

TOcApp::AddUserFormatName

TOcView::FormatList


TOcView::ReleaseObject

See Also	TOcView

Syntax

virtual void ReleaseObject();

Description

Call this function instead of using the delete operator to destroy a TOcView object. ReleaseObject decrements the view's internal reference count and dissociates the view from its window.


See Also

TOcView::SetupWindow


TOcView::Rename

TOcView

Syntax

virtual void Rename();

Description

Tells OLE when the name assigned with a compound document has changed. OLE updates its internal records. Also, the associated TOcDocument object passes the new name to any linked or embedded objects it contains.


TOcView::ScrollWindow

See Also	TOcView

Syntax

void ScrollWindow(int dx, int dy);

Description

Brings new areas of a document into view by adjusting the origin of the container window. dx and dy are horizontal and vertical offsets added to the origin. This function is usually called in response to messages from the window scroll bars or from the arrow keys.


See Also

TOcView::GetOrigin

TOcView::Origin


TOcView::SetLink

See Also	TOcView

Syntax

void SetLink(bool pasteLink);

Description

Sets an internal flag that determines whether Paste operations create linked or embedded objects. More specifically, SetLink alters the priority of the document's registered Clipboard formats. You set the original priorities with the first parameter of the REGFORMAT macro. If pasteLink is true, then SetLink moves the Link Source format to the top of the list. If pasteLink is false, it restores the Link Source format to its original position behind Embed Source.

It is usually not necessary to call SetLink directly because the Paste method calls it for you.


See Also

Registration Macros (OWL.HLP)

TOcView::Paste


TOcView::SetOcData

Syntax

void SetOcData(TOcDataProvider* ocData = 0);

Description

Sets the TOcDataProvider object for the view.


TOcView::SetOption

Syntax

void SetOption(uint 32 bit, bool state);

Description

Sets an option for the view.


TOcView::SetupWindow

See Also	TOcView

Syntax

void SetupWindow(HWND hWin, bool embedded = false);

Description

Tells the view what window is associated with it. The view sometimes sends notification messages to its window. Usually this function should be called from the SetupWindow member of the container's window class. TOleWindow performs this task automatically.

embedded should be true only in a server invoked by OLE to support a container. (Check for this condition by calling TOcAppHost::IsOptionSet and looking for the amEmbedded flag.) Passing true for embedded directs ObjectComponents to execute registration steps in a sequence that permits a container/server application to embed its own objects within itself.


See Also

OC_VIEWxxxx messages

TOcAppMode

TOcAppHost::IsOptionSet

TOleWindow::SetupWindow (OWL.HLP)


TOcView::ForwardEvent

See Also	TOcView

Syntax

Form 1

uint32 ForwardEvent(int eventId, const void far* param);

Form 2

uint32 ForwardEvent(int eventId, uint32 param = 0);

Description

Both forms send a WM_OCEVENT message to the container's window. The eventId parameter becomes the message's wParam and should be one of the message constants shown in ObjectComponents Messages. The second parameter becomes the message's lParam and may be either a pointer (Form 1) or an integer (Form 2). Which form you use depends on the information a particular event needs to send in its lParam.


See Also

ObjectComponents Messages

OC_APPxxxx messages

OC_VIEWxxxx messages

WM_OCEVENT message


TOcView::Init

See Also	TOcView

Syntax

void Init(TRegList* regList);

Description

Initializes a newly created view object. Init is called by both of the TOcView constructors. Usually you don't need to call it directly yourself. TRegList is the data type that holds all the registry keys and associated values for a single registration table. regList must be a document registration table (the structure created by the registration macros and conventionally named DocReg.)

Init makes this view the document's active view, connects with the BOCOLE support library, and registers supported Clipboard formats.


See Also

Registration Macros (OWL.HLP)


TOcView::Shutdown

See Also	TOcView

Syntax

void Shutdown();

Description

Called by the destructor of derived classes to release helper objects that the view holds internally.


See Also

TOcView::TOcView


TOcView::ActivePart

See Also	TOcView

Syntax

TOcPart* ActivePart;

Description

Remembers which part in a document is the currently active part.


See Also

TOcView::ActivatePart

TOcView::GetActivePart


TOcView::ContainerHost

Syntax

TOcContainerHost* ContainerHost;

Description

Holds the container object of the hosting application.


TOcView::Extent

See Also	TOcView

Syntax

TSize Extent;

Description

Holds the current width and height of the container window's client area. Both are measured in device units.


See Also

TOcView::GetWindowRect

TSize (OWL.HLP)


TOcView::FormatList

See Also	TOcView

Syntax

TOcFormatList FormatList;

Description

Holds information about all the Clipboard formats the compound document supports. The list is generated from information the application registers for the types of documents it supports.


See Also

TOcFormatList

TOcView::RegisterClipFormats


TOcView::Link

TOcView

Syntax

int Link;

Description

Used internally by the Paste method to adjust the priority of link source format.


TOcView::LinkFormat

Syntax

int LinkFormat;

Description

[Insert description].


TOcView::OcApp

TOcView

Syntax

TOcApp& OcApp;

Description

A view stores the application that owns it in this protected data member.


TOcView::OcData

See Also	TOcView

Syntax

TOcDataProvider* OcData;

Description

A pointer to the associated TOcDataProvider object.


See Also

TOcDataProvider


TOcView::OcDocument

See Also	TOcView

Syntax

TOcDocument& OcDocument;

Description

A view stores the document object that owns the view in this protected data member. The view object manages the appearance of a compound document, and the document object manages the data.


See Also

TOcView::GetOcDocument


TOcView::Options

TOcView	TOcView

Syntax

uint32 Options;

Description

The view options, as defined by the TOcViewOptions enum.


TOcView::OrgTitle

Syntax

TString OrgTitle;

Description

Holds the original caption string of the container's window. The caption is usually modified as the user moves from part to part within the document. When no part is active, the view restores the window's title to this original string.


TOcView::Origin

See Also	TOcView

Syntax

TPoint Origin;

Description

Holds the coordinates of the point currently mapped to the upper left corner of the container window's client area.


See Also

TOcView::GetOrigin


TOcView::RegList

See Also

Syntax

TRegList* RegList;

Description

A pointer to the associated TRegList object.


See Also

TRegList


TOcView::ServerHost

Syntax

TOcServerHost* ServerHost;

Description

Holds the server object of the hosting application.


TOcView::WinTitle

TOcView

Syntax

string WinTitle;

Description

Holds the caption string of the container's window.


TOcDragDrop struct

See Also	Linking and Embedding Structs

Header File

ocf/ocview.h

Description

Holds information that a view or a window needs in order to accept a drag and drop object. The OC_VIEWDRAG and OC_VIEWDROP messages carry a reference to this structure in their lParams. TOleView and TOleWindow process these messages for you, so you should not need to use TOcDragDrop directly unless you are programming without ObjectWindows. For examples of how to process OC_VIEWDRAG and OC_VIEWDROP messages, look at the source code for the EvOcViewDrag and EvOcViewDrop methods in TOleWindow.

Public Data Members

InitInfo

Pos

Where


See Also

ObjectComponents Header Files

OC_VIEWxxxx Messages

TOleWindow::EvOcViewDrag (OWL.HLP)

TOleWindow::EvOcViewDrop (OWL.HLP)


TOcDragDrop::InitInfo

See Also	TOcDragDrop

Syntax

TOcInitInfo far* InitInfo;

Description

When carried in an OC_VIEWDROP message, this field describes an object about to be dropped on the view. When carried in an OC_VIEWDRAG message, this field is zero.


See Also

OC_VIEWxxxx Messages

TOcInitInfo


TOcDragDrop::Pos

See Also	TOcDragDrop

Syntax

TRect* Pos;

Description

The coordinates in Pos indicate the area of the view where the user has dropped an object. The position is given in device coordinates relative to the client area.


See Also

TRect (OWL.HLP)


TOcDragDrop::Where

See Also	TOcDragDrop

Syntax

TPoint* Where;

Description

The coordinates in Where indicate the point on the view where the mouse released the object. The position is given in client area coordinates.


See Also

TPoint (OWL.HLP)


TOcViewPaint struct

See Also	Linking and Embedding Structs

Header File

ocf/ocview.h

Description

The OC_VIEWPAINT message carries a pointer to this structure in its lParam. The message notifies a server that it should update its painting of an object. The structure carries information about the area that needs repainting. Generally a program should respond by calling paint methods on the window or view that receives the message. For examples, look at the source code for TOleWindow::EvOcViewPaint.

Public Data Members

Aspect

Clip

DC

Moniker

PaintSelection

Part

Pos

UserData


See Also

ObjectComponents Header Files

OC_VIEWxxxx Messages

TOleWindow::EvOcViewPaint (OWL.HLP)


TOcViewPaint::Aspect

See Also	TOcViewPaint

Syntax

TOcAspect Aspect;

Description

Holds an enumerated value that tells how the part is to be drawn. A single object can often be drawn in more than one way. For example, the server might show the object's full contents, a miniature representation of the contents, or an icon that represents the type of object without indicating its specific contents.


See Also

TOcAspect enum


TOcViewPaint::Clip

See Also	TOcViewPaint

Syntax

TRect* Clip;

Description

Designates the area where the part should be allowed to draw. The server can clip the output to this area to avoid drawing outside its allotted space.


See Also

TRect (OWL.HLP)


TOcViewPaint::DC

TOcViewPaint

Syntax

HDC DC;

Description

Contains a handle to the device context where the repainting should occur.


TOcViewPaint::Moniker

TOcViewPaint

Syntax

TString* Moniker;

Description

The file moniker for the view or selection.


TOcViewPaint::PaintSelection

TOcViewPaint

Syntax

bool PaintSelection;

Description

A Boolean value indicating whether to paint the selection or the view.


TOcViewPaint::Part

See Also	TOcViewPaint

Syntax

TOcPart* Part;

Description

Points to the part that needs to be redrawn. This member can be used to ask the part to repaint itself. In the current implementation of ObjectComponents, this member is not used.


See Also

TOcPart


TOcViewPaint::Pos

See Also	TOcViewPaint

Syntax

TRect* Pos;

Description

Specifies the upper left corner of the server object that has become invalid and needs repainting.


See Also

TRect (OWL.HLP)


TOcViewPaint::UserData

TOcViewPaint

Syntax

void* UserData;

Description

The data to paint when painting a selection.


TOcSaveLoad class

See Also

Header File

ocf/ocview.h

Base Class

TOcSaveLoad

Description

Holds information that a view uses when loading and saving its OLE object parts. The OC_VIEWLOADPART and OC_VIEWSAVEPART messages carry a pointer to this structure in their lParams.

TOleView processes the load and save messages for you. If you are programming with the ObjectWindows Doc/View model, then you do not need to use the TOcSaveLoad structure directly. For examples that show how to process the load and save messages, look at the source code for the TOleView::EvOcViewLoadPart and TOleView::EvOcViewSavePart methods in TOleView.

Public Constructor

TOcSaveLoad

Public Data Members

StorageI

SameAsLoad

Remember

SaveSelection

UserData


See Also

OC_VIEWxxxx messages

ObjectComponents Header Files

TOleView::EvOcViewLoadPart (OWL.HLP)

TOleView::EvOcViewSavePart (OWL.HLP)


TOcSaveLoad::TOcSaveLoad

TOcRemView

Syntax

TOcSaveLoad (IStorage* storageI, bool sameAsLoad = true, bool remember = false, bool saveSelection = false, void* userData = 0);

Description

Creates a TOcSaveLoad object with data members initialized to the values you specify.

Destructor

The destructor for TOcRemView is private. ObjectComponents releases the object when it is no longer needed.


TOcSaveLoad::Remember

TOcSaveLoad

Syntax

bool Release;

Description

Returns true if the IStorage pointer should be freed after saving or loading.


TOcSaveLoad::SameAsLoad

TOcSaveLoad

Syntax

bool SameAsLoad;

Description

Returns true if the IStorage pointer is the same one used for loading.


TOcSaveLoad::SaveSelection

TOcSaveLoad

Syntax

bool SaveSelection;

Description

Returns true if only the selection should be saved instead of the entire view.


TOcSaveLoad::StorageI

TOcSaveLoad

Syntax

IStorage far* StorageI;

Description

Points to the storage object. ObjectComponents implements the standard OLE IStorage interface in TOcStorage, so TOcStorage can be used to construct an IStorage.


TOcSaveLoad::UserData

TOcSaveLoad

Syntax

void* UserData;

Description

Contains a pointer to the data block that can be saved or loaded.


TOcToolBarInfo struct

Linking and Embedding Structs

Header File

ocf/ocview.h

Description

The OC_VIEWSHOWTOOLS message carries a pointer to this structure in its lParam. The message asks a server for handles to its tool bars so the container can display them in its own window. This happens during in-place editing when the user opens an object in the container in order to modify it.

The structure has four fields, allowing the server to return handles for up to four tool bars. Each tool bar occupies a different edge of the container's client area.

For examples, look at the source code for TOleWindow::EvOcViewShowTools. The default implementations of these methods allow a single tool bar at the top of the client area. To give the container more tool bars, handle the OC_VIEWSHOWTOOLS message directly yourself.

Public Data Members

HBottomTB

HFrame

HLeftTB

HRightTB

HTopTB

Show


See Also

ObjectComponents Header Files

OC_VIEWxxxx messages

TOleWindow::EvOcViewShowTools (OWL.HLP)


TOcToolBarInfo::HBottomTB

TOcToolBarInfo

Syntax

HWND HBottomTB;

Description

Holds a handle to the tool bar that the server wants to place at the bottom of the container's client area.


TOcToolBarInfo::HFrame

TOcToolBarInfo

Syntax

HWND HFrame;

Description

If Show is true and the server is being asked to display its tool bar, then HFrame holds a handle to the frame window where the tool bar is to appear. If Show is false, then HFrame holds a handle to the server's own frame window.


See Also

TOcToolBarInfo::Show


TOcToolBarInfo::HLeftTB

TOcToolBarInfo

Syntax

HWND HLeftTB;

Description

Holds a handle to the tool bar that the server wants to place at the left edge of the container's client area.


TOcToolBarInfo::HRightTB

TOcToolBarInfo

Syntax

HWND HRightTB;

Description

Holds a handle to the tool bar that the server wants to place at the right edge of the container's client area.


TOcToolBarInfo::HTopTB

TOcToolBarInfo

Syntax

HWND HTopTB;

Description

Holds a handle to the tool bar that the server wants to place at the top of the container's client area.


TOcToolBarInfo::Show

TOcToolBarInfo

Syntax

bool Show;

Description

Is true to ask that the server display its tool bar or false to request that the server hide the tool bar.


TOcPartSize class

Header File

ocf/ocview.h

Description

Obtains the size of the rectangle that encloses the selection.

Public Constructor

TOcPartSize

Public Data Members

Moniker

PartRect

Selection

UserData


TOcPartSize Public Constructors
TOcPartSize::TOcPartSize

TOcPartSize

Syntax 1

TOcPartSize();

Syntax 2

TOcPartSize(TRect rect, bool selection = false, TString* moniker = 0, void* userData = 0);

Syntax 3

TOcPartSize(bool selection, TString* moniker = 0, void* userData = 0)

Description

Creates a TOcPartSize object.


TOcPartSize::Moniker

TOcPartSize

Syntax

TString* Moniker;

Description

The file moniker for the embedded object or selection.


TOcPartSize::PartRect

TOcPartSize

Syntax

TRect PartRect;

Description

Contains the rectangle enclosing the embedded object or selection.


TOcPartSize::Selection

TOcPartSize

Syntax

TRect PartRect;

Description

Returns true if the rectangle (PartRect) contains a selection; returns false if the rectangle contains an embedded object.


TOcPartSize::UserData

TOcPartSize

Syntax

void* UserData;

Description

Contains a pointer to the data block.


TOcItemName class

Header File

ocf/ocview.h

Description

Contains the name of an object or selection.

Public Constructor

TOcItemName

Public Data Members

Name

Selection


TOcItemName::TOcItemName

TOcItemName

Syntax 1

TOcItemName();

Description

Creates a TOcItemName object.

Syntax 2

TOcItemName(bool selection);

Description

Creates a TOcItemName object and initializes the Selection data member to selection.


TOcItemName::Selection

TOcItemName

Syntax

bool Selection;

Description

A Boolean value indicating whether the Name data member refers to the object or to a selection within the object.


TOcItemName::Name

TOcItemName

Syntax

TString Name;

Description

The name of the object or selection.


TOcFormatData class

Header File

ocf/ocview.h

Description

Information about data that is used in cut and paste operations.

Public Constructor

TOcFormatData

Public Data Members

Format

Handle

Paste

UserData

Where


TOcFormatData::TOcFormatData

TOcFormatData

Syntax

TOcFormatData(TOcFormat& format, void* userData = 0, HANDLE handle = 0, bool paste = false, TPoint far* where = 0)

Description

Creates a TOcFormatData object with data members initialized to the values you specify.


TOcFormatData::Handle

TOcFormatData

Syntax

HANDLE Handle;

Description

The handle for the data.


TOcFormatData::Format

See Also	TOcFormatData

Syntax

TOcFormat& Format;

Description

The data format.


See Also

TOcFormat


TOcFormatData::Paste

TOcFormatData

Syntax

bool Paste;

Description

A Boolean value indicating whether or not the data is being pasted.


TOcFormatData::UserData

TOcFormatData

Syntax

void* UserData;

Description

The data.


TOcFormatData::Where

TOcFormatData

Syntax

TPoint far* Where;

Description

Where the data is being pasted.


TOcItemLink class

Header File

ocf/ocview.h

Description

Contains the moniker for an object or selection.

Public Constructors

TOcItemLink

Public Data Members

Moniker

OcLinkView


TOcItemLink::TOcItemLink

TOcItemLink

Syntax

TOcItemLink(const char far* moniker, TOcLinkView* view) : Moniker(moniker), OcLinkView(view);

Description

Creates a TOcItemLink object with data members initialized to the values you specify.


TOcLinkView::Moniker

TOcItemLink

Syntax

const char far* Moniker;

Description

The moniker for the object or selection.


TOcItemLink::OcLinkView

TOcItemLink

Syntax

TOcLinkView* OcLinkView;;

Description

The associated TOcLinkView object.


See Also

TOcLinkView


TOcScaleFactor class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

The TOcScaleFactor class carries information from a container to a server about how the container wants to scale its document. For example, if the container has a Zoom command and the user chooses to magnify the document to 120%, the server should match the scaling factor when it draws objects embedded in the container.

ObjectComponents passes a reference to an TOcScaleFactor object in the lParam of OC_VIEWGETSCALE and OC_VIEWSETSCALE messages. When a container receives OC_VIEWGETSCALE, it fills in the object with scaling information. When a server receives the OC_VIEWSETSCALE information, it reads the scaling values and can use them in its paint procedure.

TOcScaleFactor stores scaling information in its two TSize members, SiteSize and PartSize. The names refer to the area where the container wants to draw an object (the site) and the object itself (the part.) The values in the members need not be the actual size of the site or the part, however. What matters is the ratio of the two sizes. If the SiteSize values are twice as large as the PartSize values, then the server is being asked to draw the object at twice its default size.

If you are programming with ObjectWindows, then the TOleWindow class takes care of scaling for you. For examples showing how to handle scaling without the benefit of ObjectWindows, look at the source code for the following TOleWindow methods: EvOcViewGetScale, EvOcViewSetScale, and SetupDC.

Public Data Members

PartSize

SiteSize

Public Constructor

TOcScaleFactor

Public Member Functions

operator =

operator =

GetScale

GetScaleFactor

IsZoomed

Reset

SetScale


See Also

OC_VIEWxxxx Messages

TOleWindow::EvOcViewGetScale (OWL.HLP)

TOleWindow::EvOcViewSetScale (OWL.HLP)

TOleWindow::SetupDC (OWL.HLP)

TSize (OWL.HLP)


TOcScaleFactor::PartSize

See Also	TOcScaleFactor

Syntax

TSize PartSize;

Description

Holds two values describing the default horizontal and vertical extent of a server's object. The values in PartSize do not need to be actual measurements. What matters is the ratio of the values here to the values in SiteSize. That ratio determines how an image should be scaled.


See Also

TOcScaleFactor::SiteSize

TSize (OWL.HLP)


TOcScaleFactor::SiteSize

See Also	TOcScaleFactor

Syntax

TSize SiteSize;

Description

Holds two values describing the horizontal and vertical extent of the area a container has allotted for displaying a linked or embedded object. The values in SiteSize do not need to be actual measurements. What matters is the ratio of the values here to the values in PartSize. That ratio determines how an image should be scaled.


See Also

TOcScaleFactor::PartSize

TSize (OWL.HLP)


TOcScaleFactor::TOcScaleFactor

See Also	TOcScaleFactor

Syntax 1

TOcScaleFactor();

Description

Initializes the site and part extents to 1 so the scaling factor is 100%.

Syntax 2

TOcScaleFactor(const RECT& siteRect, const TSize& partSize);

Description

Bases the initial scaling factor on the values in the given rectangle structure and size object. Calculates the extents of the rectangle siteRect and sets them in SiteSize. Copies partSize to PartSize.

Syntax 3

TOcScaleFactor(const BOleScaleFactor far& scaleFactor);

Description

Bases the initial scaling factor on the values in scaleFactor. BOleScaleFactor is a structure that the BOCOLE support library uses internally to carry scaling information. You should not have to use the structure directly.

Destructor

~TOcScaleFactor();

Remarks

Usually you do not have to construct a TOcScaleFactor object directly. ObjectComponents creates it for you and passes it in the OC_VIEWGETSCALE or OC_VIEWSETSCALE message.


See Also

OC_VIEWxxxx Messages

TOcScaleFactor::PartSize

TOcScaleFactor::SiteSize

TSize (OWL.HLP)


TOcScaleFactor::operator =

See Also	TOcScaleFactor

Syntax 1

TOcScaleFactor& operator =(const TOcScaleInfo far& scaleInfo);

Description

Copies from one TOcScaleInfo into another.

Syntax 2

TOcScaleFactor& operator =(const TOcScaleFactor& scaleFactor);

Both forms of the assignment operator copy the values from one scaling object into another.

Description

Copies from one TOcScaleFactor into another.


See Also

OC_VIEWxxxx Messages


TOcScaleFactor::GetScale

See Also	TOcScaleFactor

Syntax

uint16 GetScale();

Description

Retrieves a percentage value expressing the ratio of the part's size to the site's size. For example, if the part size is 20 x 20 and the site size is 40 x 40, then GetScale returns 200.


See Also

TOcScaleFactor::SetScale


TOcScaleFactor::GetScaleFactor

TOcScaleFactor

Syntax

void GetScaleFactor(TOcScaleInfo far& scaleInfo) const;

Description

Fills in scaleFactor with values from the TOcScaleInfo object.


TOcScaleFactor::IsZoomed

TOcScaleFactor

Syntax

bool IsZoomed();

Description

Returns true if the sizes stored for the part and the site do not match.


TOcScaleFactor::Reset

TOcScaleFactor

Syntax

void Reset();

Description

Resets the scaling.


TOcScaleFactor::SetScale

See Also	TOcScaleFactor

Syntax

void SetScale(uint16 percent);

Description

Sets the ratio of the part's size to the site's size. More specifically, SetScale sets the size of the part to 100 and the size of the site to percent.


See Also

TOcScaleFactor::GetScale


OC_VIEWxxxx messages

See Also	Linking and Embedding Messages

Header File

ocf/ocview.h

Description

These messages are sent from ObjectComponents to the application's window procedure. They notify the application of signals and events that come from the OLE system. The actual message sent is WM_OCEVENT. The constants in the table below are carried in the message's wParam and identify particular events. To find out what each message carries in its lParam, see ObjectComponents messages.

Constant	Meaning

OC_VIEWATTACHWINDOW	Asks the server window to attach to its own frame window or the container's window.

OC_VIEWBORDERSPACEREQ	Asks whether the server can have space in the container's window for in-place editing tools.

OC_VIEWBORDERSPACESET	Requests border space for in-place editing tools in the container's view.

OC_VIEWBREAKLINK	Asks server to break a link to the currently selected data.

OC_VIEWCLIPDATA	Asks the server for Clipboard data in a particular format.

OC_VIEWCLOSE	Tells server to close this remote view.

OC_VIEWDRAG	Requests visual feedback during a drag operation.

OC_VIEWDOVERB	Asks the server to invoke one of its verbs.

OC_VIEWDROP	Accepts a dropped object.

OC_VIEWGETITEMNAME	Asks the server for a moniker identifying the currently selected data.

OC_VIEWGETPALETTE	Asks the server for the palette it uses to paint its object.

OC_VIEWGETSCALE	Asks the container to give scaling information.

OC_VIEWGETSITERECT	Asks container for the site rectangle.

OC_VIEWINSMENUS	Asks the server to insert its menus in the menu bar for in-place editing.

OC_VIEWLOADPART	Asks the server to load its document. (The server's document contains one part.)

OC_VIEWOPENDOC	Asks the server for the extents of its open document.

OC_VIEWPAINT	Asks the server to paint a remote view of its document.

OC_VIEWPARTACTIVATE	Indicates that an embedded part has become active.

OC_VIEWPARTINVALID	Indicates that a part needs repainting.

OC_VIEWPARTSIZE	Asks the server for the extents of its object.

OC_VIEWPASTEOBJECT	Asks the server to paste an object into its document.

OC_VIEWSAVEPART	Asks the server to save its document. (The server's document contains one part.)

OC_VIEWSCROLL	Asks the client to scroll its view because the user is trying to drag something off the edge.

OC_VIEWSETSCALE	Asks the server to handle scaling.

OC_VIEWSETLINK	Asks server to create a link to the currently selected data.

OC_VIEWSETSITERECT	Asks the container to set the site rectangle.

OC_VIEWSETTITLE	Tells the container to append the name of the server to its window caption. Sent when beginning in-place editing.

OC_VIEWSHOWTOOLS	Asks the server to display its tool bars in the container's window for in-place editing.

OC_VIEWTITLE	Gets the title displayed in the view's window.


See Also

Event Handlers (OWL.HLP)

Messages and Windows

ObjectComponents Messages


TOcContainerHost class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

Contains a function for each ObjectComponents message that an OLE container can receive. The functions are pure virtual, which means they have no implementation. You control how your container handles each message by implementing the virtual functions and passing a TOcContainerHost object to the TOcView constructor.

By default, containers use the TOcContainerHostMsg class (a TOcContainerHostMsg object, not a TOcContainerHost object, is passed to the TOcView constructor). The TOcContainerHostMsg class is derived from the TOcContainerHost class, but the TOcContainerHostMsg class has implementations for each of the virtual functions. The implementations simply forward container messages to the view window, where they can be handled in the view window procedure as normal.

Public Member Functions

EvOcPartInvalid

EvOcViewBorderSpaceReq

EvOcViewBorderSpaceSet

EvOcViewDrag

EvOcViewDrop

EvOcViewGetScale

EvOcViewGetSiteRect

EvOcViewOpenDoc

EvOcViewPartActivate

EvOcViewPasteObject

EvOcViewScroll

EvOcViewSetSiteRect

EvOcViewSetTitle

EvOcViewTitle

ReleaseOcObject


See Also

TOcView::TOcView

TOcContainerHostMsg

TOcServerHost


TOcContainerHost::EvOcPartInvalid

See Also	TOcContainerHost

Syntax

virtual bool EvOcPartInvalid(TOcPartChangeInfo& part) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWPARTINVALID message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewBorderSpaceReq

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewBorderSpaceReq(const TRect far* rect) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWBORDERSPACEREQ message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewBorderSpaceSet

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewBorderSpaceSet(const TRect far* rect) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWBORDERSPACESET message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewDrag

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewDrag(TOcDragDrop far& ddInfo) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWDRAG message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewDrop

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewDrop(TOcDragDrop far& ddInfo) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWDROP message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewGetScale

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewGetScale(TOcScaleFactor& scaleFactor) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWGETSCALE message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewGetSiteRect

See Also	TOcContainerHost

Syntax 1

virtual bool EvOcViewGetSiteRect(TOcSiteRect& sr);

Syntax 2

virtual bool EvOcViewGetSiteRect(TRect far* rect);

Description

Implement these functions to control how the container responds to the OC_VIEWBORDERSPACEREQ message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewOpenDoc

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewOpenDoc(const char far* path) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWOPENDOC message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewPartActivate

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewPartActivate(TOcPart& ocPart) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWPARTACTIVATE message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewPasteObject

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewPasteObject(TOcInitInfo& init) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWPASTEOBJECT message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewScroll

See Also	TOcContainerHost

Syntax

virtual bool EvOcViewScroll(TOcScrollDir scrollDir);

Description

Implement this function to control how the container responds to the OC_VIEWSCROLL message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewSetSiteRect

See Also	TOcContainerHost

Syntax 1

virtual bool EvOcViewSetSiteRect(TOcSiteRect& sr) = 0;

Syntax 2

virtual bool EvOcViewSetSiteRect(TRect far* rect) = 0;

Description

Implement these functions to control how the container responds to the OC_VIEWSETSITERECT message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewSetTitle

See Also	TOcContainerHost

Syntax

virtual void EvOcViewSetTitle(const char far* title) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWSETTITLE message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::EvOcViewTitle

See Also	TOcContainerHost

Syntax

virtual const char far* EvOcViewTitle() = 0;

Description

Implement this function to control how the container responds to the OC_VIEWTITLE message.


See also

OC_VIEWxxxx Messages


TOcContainerHost::ReleaseOcObject

TOcContainerHost

Syntax

virtual void ReleaseOcObject() = 0;

Description

Deletes the TOcContainerHost object.


TOcServerHost class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

Contains a function for each ObjectComponents message that an OLE server can receive. The functions are pure virtual, which means they have no implementation. You control how your server handles each message by implementing the virtual functions and passing a TOcServerHost object to the TOcView constructor.

By default, containers use the TOcServerHostMsg class (a TOcServerHostMsg object, not a TOcServerHost object, is passed to the TOcView constructor). The TOcServerHostMsg class is derived from the TOcServerHost class, but the TOcServerHostMsg class has implementations for each of the virtual functions. The implementations simply forward server messages to the view window, where they can be handled in the view window procedure as normal.

Public Member Functions

EvOcGetWindow

EvOcViewAttachWindow

EvOcViewBreakLink

EvOcViewClipData

EvOcViewClose

EvOcViewDoVerb

EvOcViewDrag

EvOcViewGetItemName

EvOcViewGetPalette

EvOcViewInsMenus

EvOcViewLoadPart

EvOcViewPaint

EvOcViewPartSize

EvOcViewSavePart

EvOcViewSetLink

EvOcViewSetScale

EvOcViewSetTitle

EvOcViewShowTools

ReleaseOcObject


See Also

TOcContainerHost

TOcServerHostMsg


TOcServerHost::EvOcGetWindow

See Also	TOcServerHost

Syntax

virtual HWND EvOcGetWindow() const = 0;

Description

Implement this function to control how the container responds to the OC_VIEWGETWINDOW message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewAttachWindow

See Also	TOcServerHost

Syntax

virtual bool EvOcViewAttachWindow(bool attach) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWATTACHWINDOW message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewBreakLink

See Also	TOcServerHost

Syntax

virtual bool EvOcViewBreakLink(TOcLinkView& view) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWBREAKLINK message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewClipData

See Also	TOcServerHost

Syntax

virtual bool EvOcViewClipData(TOcFormatData far& format) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWCLIPDATA message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewClose

See Also	TOcServerHost

Syntax

virtual bool EvOcViewClose() = 0;

Description

Implement this function to control how the container responds to the OC_VIEWCLOSE message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewDoVerb

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewDoVerb(uint ver) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWDOVERB message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewDrag

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewDrag(TOcDragDrop far& ddInfo) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWDRAG message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewGetItemName

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewGetItemName(TOcItemName* item) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWGETITEMNAME message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewGetPalette

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewGetPalette(LOGPALETTE far* far* palette) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWGETPALETTE message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewInsMenus

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewInsMenus(TOcMenuDescr far& sharedMenu) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWINSMENUS message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewLoadPart

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewLoadPart(TOcSaveLoad far& ocLoad) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWLOADPART message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewPaint

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewPaint(TOcViewPaint far& vp) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWPAINT message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewPartSize

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewPartSize(TOcPartSize far& size) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWPARTSIZE message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewSavePart

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewSavePart(TOcSaveLoad far& ocSave) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWSAVEPART message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewSetLink

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewSetLink(TOcLinkView& view) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWSETLINK message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewSetScale

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewSetScale(TOcScaleFactor& scaleFactor) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWSETSCALE message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewSetTitle

See Also 	TOcServerHost

Syntax

virtual void EvOcViewSetTitle(const char far* title) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWSETTITLE message.


See also

OC_VIEWxxxx Messages


TOcServerHost::EvOcViewShowTools

See Also 	TOcServerHost

Syntax

virtual bool EvOcViewShowTools(TOcToolBarInfo far& tbi) = 0;

Description

Implement this function to control how the container responds to the OC_VIEWSHOWTOOLS message.


See also

OC_VIEWxxxx Messages


TOcServerHost::ReleaseOcObject

TOcServerHost

Syntax

virtual void ReleaseOcObject();

Description

Deletes the TOcServerHost object.


TOcContainerHostMsg class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

Sends ObjectComponents messages to the view window, where they can be handled in the view window procedure as normal. A TOcContainerHostMsg object is created automatically by the TOcView constructor unless you specify otherwise.

Public Member Functions

EvOcGetWindow

EvOcPartInvalid

EvOcViewBorderSpaceReq

EvOcViewBorderSpaceSet

EvOcViewClose

EvOcViewDoVerb

EvOcViewDrag

EvOcViewDrop

EvOcViewInsMenus

EvOcViewOpenDoc

EvOcViewPasteObject

EvOcViewScroll

EvOcViewSetScale

EvOcViewSetTitle

EvOcViewShowTools

EvOcViewTitle

Protected Member Functions

ForwardEvent


See Also

TOcServerHost

TOcContainerHostMsg

TOcView::TOcView


TOcContainerHostMsg::EvOcViewOpenDoc

See Also	TOcContainerHostMsg

Syntax

virtual bool EvOcViewOpenDoc(const char far* path);

Description

Sends the OC_VIEWOPENDOC message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewTitle

See Also 	TOcContainerHostMsg

Syntax

virtual const char far* EvOcViewTitle();

Description

Sends the OC_VIEWTITLE message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewSetTitle

See Also 	TOcContainerHostMsg

Syntax

virtual void EvOcViewSetTitle(const char far* title);

Description

Sends the OC_VIEWSETTITLE message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewBorderSpaceReq

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewBorderSpaceReq(const TRect far* rect);

Description

Sends the OC_VIEWBORDERSPACEREQ message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewBorderSpaceSet

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewBorderSpaceSet(const TRect far* rect);

Description

Sends the OC_VIEWBORDERSPACESET message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewDrag

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewDrag(TOcDragDrop far& ddInfo);

Description

Sends the OC_VIEWDRAG message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewDrop

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewDrop(TOcDragDrop far& ddInfo);

Description

Sends the OC_VIEWDROP message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewScroll

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewScroll(TOcScrollDir scrollDir);

Description

Sends the OC_VIEWSCROLL message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcPartInvalid

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcPartInvalid(TOcPartChangeInfo& part);

Description

Sends the OC_VIEWPARTINVALID message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewPasteObject

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewPasteObject(TOcInitInfo& init);

Description

Sends the OC_VIEWPASTEOBJECT message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewInsMenus

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewInsMenus(TOcMenuDescr far& sharedMenu);

Description

Sends the OC_VIEWINSMENUS message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewShowTools

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewShowTools(TOcToolBarInfo far& tbi);

Description

Sends the OC_VIEWSHOWTOOLS message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewClose

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewClose();

Description

Sends the OC_VIEWCLOSE message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewSetScale

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewSetScale(TOcScaleFactor& scaleFactor);

Description

Sends the OC_VIEWSETSCALE message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcViewDoVerb

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcViewDoVerb(uint verb);

Description

Sends the OC_VIEWDOVERB message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::EvOcGetWindow

See Also 	TOcContainerHostMsg

Syntax

virtual bool EvOcGetWindow() const;

Description

Sends the OC_VIEWGETWINDOW message to the view window.


See also

OC_VIEWxxxx Messages


TOcContainerHostMsg::ForwardEvent

See Also 	TOcContainerHostMsg

Syntax 1

uint32 ForwardEvent(int eventId, const void far* param);

Syntax 2

uint32 ForwardEvent(int eventId, uint32 param = 0);

Description

Forwards an event to the view window. This function is used by all the event-handling functions of the TOcContainerHostMsg class.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg class

See Also	Linking and Embedding Classes

Header File

ocf/ocview.h

Description

Sends ObjectComponents messages to the view window, where they can be handled in the view window procedure as normal. A TOcContainerHostMsg object is created automatically by the TOcView constructor unless you specify otherwise.

Public Member Functions

EvOcGetWindow

EvOcViewAttachWindow

EvOcViewBreakLink

EvOcViewClipData

EvOcViewClose

EvOcViewDoVerb

EvOcViewDrag

EvOcViewGetItemName

EvOcViewGetPalette

EvOcViewInsMenus

EvOcViewLoadPart

EvOcViewPaint

EvOcViewPartSize

EvOcViewSavePart

EvOcViewSetData

EvOcViewSetLink

EvOcViewSetScale

EvOcViewSetTitle

EvOcViewShowTools

ReleaseOcObject

Protected Member Functions

ForwardEvent


See Also

TOcView::TOcView

TOcServerHost

TOcContainerHostMsg


TOcServerHostMsg::EvOcGetWindow

STOcContainerHostMsg

Syntax

virtual HWND EvOcGetWindow() const;

Description

Returns the handle for the view window.


TOcServerHostMsg::EvOcViewAttachWindow

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewAttachWindow(bool attach);

Description

Sends the OC_VIEWATTACHWINDOW message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewBreakLink

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewBreakLink(TOcLinkView& view);

Description

Sends the OC_VIEWBREAKLINK message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewClipData

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewClipData(TOcFormatData far& format);

Description

Sends the OC_VIEWCLIPDATA message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewClose

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewClose();

Description

Sends the OC_VIEWCLOSE message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewDoVerb

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewDoVerb(uint verb);

Description

Sends the OC_VIEWDOVERB message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewDrag

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewDrag(TOcDragDrop far& ddInfo);

Description

Sends the OC_VIEWDRAG message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewGetItemName

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewGetItemName(TOcItemName& item);

Description

Sends the OC_VIEWGETITEMNAME message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewGetPalette

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewGetPalette(LOGPALETTE far* far* palette);

Description

Sends the OC_VIEWGETPALETTE message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewInsMenus

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewInsMenus(TOcMenuDescr far& sharedMenu);

Description

Sends the OC_VIEWINSMENUS message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewLoadPart

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewLoadPart(TOcSaveLoad far& ocLoad);

Description

Sends the OC_VIEWLOADPART message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewPaint

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewPaint(TOcViewPaint far& vp);

Description

Sends the OC_VIEWPAINT message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewPartSize

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewPartSize(TOcPartSize far& size);

Description

Sends the OC_VIEWPARTSIZE message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewSavePart

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewSavePart(TOcSaveLoad far& ocSave);

Description

Sends the OC_VIEWSAVEPART message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewSetData

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewSetData(TOcFormatData far& format);

Description

Sends the OC_VIEWSETDATA message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewSetLink

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewSetLink(TOcLinkView& view);

Description

Sends the OC_VIEWSETLINK message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewSetScale

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewSetScale(TOcScaleFarctor& scaleFactor);

Description

Sends the OC_VIEWSETSCALE message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewSetTitle

See Also	TOcServerHostMsg

Syntax

virtual void EvOcViewSetTitle(const char far* title);

Description

Sends the OC_VIEWSETTITLE message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::EvOcViewShowTools

See Also	TOcServerHostMsg

Syntax

virtual bool EvOcViewShowTools(TOcToolBarInfo far& tbi);

Description

Sends the OC_VIEWSHOWTOOLS message to the view window.


See also

OC_VIEWxxxx Messages


TOcServerHostMsg::ReleaseOcObject

TOcServerHostMsg

Syntax

virtual void ReleaseOcObject();

Description

Deletes the TOcServerHostMsg object.


TOcServerHostMsg::ForwardEvent

See Also

Syntax 1

uint32 ForwardEvent(int eventId, const void far* param);

Description

Forwards an event to the view window.

Syntax 2

uint32 ForwardEvent(int eventId, uint32 param);

Description

Forwards an event to the view window.


See also

OC_VIEWxxxx Messages


TOcSiteRect class

See Also

Header File

ocf/ocview.h

Description

The rectangular area in which an object is embedded.

Public Constructor

TOcSiteRect

Public Data Members

Rect

Part


See Also

OC_VIEWxxxx Messages


TOcSiteRect::TOcSiteRect

TOcSiteRect

Syntax

TOcSiteRect();

Description

Creates a TOcSiteRect object.

Syntax

TOcSiteRect(TOcPart *part, const TRect& rect);

Description

Creates a TOcSiteRect object with data members initialized to the values you specify.

Remarks

Used for determining or specifying the coordinates of a linked or embedded object.


TOcSiteRect::Rect

TOcSiteRect

Syntax

TRect Rect;

Description

The rectangular area in which the object is embedded.


TOcSiteRect::Part

TOcSiteRect

Syntax

TOcPart *Part;

Description

The object or selection that is embedded.


TOcViewOptions enum

See Also

Header File

ocf/ocview.h

Description

View options. Use this enumerated type with the TOcView::Options function.

Syntax

enum TOcViewOptions;

Description

These are the constants for the possible view options:

Constant	Value	Description

voNoInPlace	0x0001	The view doesn’t allow in-place activation.

voNoNestedInPlace	0x0002	The view doesn’t allow nested in-place activation.

voNoInPlaceServer	0x0004	The view doesn’t allow in-place server activation.


See Also

TOcView::Options


OC_CTRLEVENTxxxx Messages

See Also	Linking and Embedding Messages

Header File

ocf/ocview.h

Description

These messages are sent from a control to a container through ObjectComponents.

The actual message sent is WM_OCEVENT. The constants in the table below are carried in the message's wParam and identify particular events. To find out what each message carries in its lParam, see ObjectComponents messages.

Constant	Meaning

OC_CTRLEVENT_FOCUS	The control got or lost focus.

OC_CTRLEVENT_PROPERTYCHANGE	A property of the control has changed.

OC_CTRLEVENT_PROPERTYREQUESTEDIT	A property of the control is about to change.

OC_CTRLEVENT_CLICK	The mouse was clicked on the control.

OC_CTRLEVENT_DBLCLICK	The mouse was double-clicked on the control.

OC_CTRLEVENT_MOUSEDOWN	A mouse button was held down on the control.

OC_CTRLEVENT_MOUSEMOVE	The mouse was moved on the control.

OC_CTRLEVENT_MOUSEUP	A mouse button was released on the control.

OC_CTRLEVENT_KEYDOWN	A key was pressed when the control was focused.

OC_CTRLEVENT_KEYUP	A key was released when the control was focused.

OC_CTRLEVENT_ERROREVENT	An error occurred on the control.

OC_CTRLEVENT_CUSTOMEVENT	A custom event occurred on the control.


See Also

Event Handlers (OWL.HLP)

Messages and Windows

ObjectComponents Messages


OC_AMBIENT_GETxxxx Messages

See Also	Linking and Embedding Messages

Header File

ocf/ocview.h

Description

These messages are sent from a control to its container through ObjectComponents. The control may use the information it receives to integrate itself into the container’s user interface.

The actual message sent is WM_OCEVENT. The constants in the table below are carried in the message's wParam and identify particular events. To find out what each message carries in its lParam, see ObjectComponents messages.

Constant	Meaning

OC_AMBIENT_GETBACKCOLOR	The control wants the container’s background color.

OC_AMBIENT_GETFORECOLOR	The control wants the container’s foreground color.

OC_AMBIENT_GETSHOWGRABHANDLES	The control wants to know whether the container displays grab handles.

OC_AMBIENT_GETUIDEAD	The control wants to know whether the container is accepting input from the user.

OC_AMBIENT_GETSUPPORTSMNEMONICS	The control wants to know whether the container supports mnemonics.

OC_AMBIENT_GETSHOWHATCHING	The control wants to know whether the container shows hatching.

OC_AMBIENT_GETDISPLAYASDEFAULT	The control wants to know whether it should display itself as the default control (button controls only).

OC_AMBIENT_GETTEXTALIGN	The control wants to know how text is aligned in the container.

OC_AMBIENT_GETMESSAGEREFLECT	The control wants to know whether the container’s messages are reflected to the control.

OC_AMBIENT_GETLOCALEID	The control wants the container’s locale identifier.

OC_AMBIENT_GETUSERMODE	The control wants to know whether the container is in user mode (instead of design mode).

OC_AMBIENT_GETDISPLAYMODE	The control wants the container’s display mode.

OC_AMBIENT_GETSCALEUNITS	The control wants the container’s scale units.

OC_AMBIENT_GETFONT	The control wants the container’s font.


See Also

Event Handlers (OWL.HLP)

Messages and Windows

ObjectComponents Messages


OC_AMBIENT_SETxxxx Messages

See Also	Linking and Embedding Messages

Header File

ocf/ocview.h

Description

These messages are sent from a control to its container through ObjectComponents. The container may use the information it receives to accomodate the control’s user interface.

The actual message sent is WM_OCEVENT. The constants in the table below are carried in the message's wParam and identify particular events. To find out what each message carries in its lParam, see ObjectComponents messages.

Constant	Meaning

OC_AMBIENT_SETBACKCOLOR	The control wants to set the container’s background color.

OC_AMBIENT_SETFORECOLOR	The control wants to set the container’s foreground color.

OC_AMBIENT_SETSHOWGRABHANDLES	The control wants to set whether the container displays grab handles.

OC_AMBIENT_SETUIDEAD	The control wants to set whether the container is accepting input from the user.

OC_AMBIENT_SETSUPPORTSMNEMONICS	The control wants to set whether the container supports mnemonics.

OC_AMBIENT_SETSHOWHATCHING	The control wants to set whether the container shows hatching.

OC_AMBIENT_SETDISPLAYASDEFAULT	The control wants to set whether it should display itself as the default control (button controls only).

OC_AMBIENT_SETTEXTALIGN	The control wants to set how text is aligned in the container.

OC_AMBIENT_SETMESSAGEREFLECT	The control wants to set whether the container’s messages are reflected to the control.

OC_AMBIENT_SETLOCALEID	The control wants to set the container’s locale identifier.

OC_AMBIENT_SETUSERMODE	The control wants to set whether the container is in user mode (instead of design mode).

OC_AMBIENT_SETDISPLAYMODE	The control wants to set the container’s display mode.

OC_AMBIENT_SETSCALEUNITS	The control wants to set the container’s scale units.

OC_AMBIENT_SETFONT	The control wants to set the container’s font.


See Also

Event Handlers (OWL.HLP)

Messages and Windows

ObjectComponents Messages


OC_USEREVENT Message

See Also	Linking and Embedding Messages

Header File

ocf/ocview.h

Description

This message is sent from a control to its container through ObjectComponents. The message indicates that a custom (nonstandard) event has occurred.

The actual message sent is WM_OCEVENT. The constants in the table below are carried in the message's wParam and identify particular events. To find out what each message carries in its lParam, consult the control’s documentation.

Constant	Meaning

OC_USEREVENT	A custom event has occurred on the control.


See Also

Event Handlers (OWL.HLP)

Messages and Windows

ObjectComponents Messages


_ICLASS macro

General OLE Classes, Macros, and Type Definitions

Header File

ocf/oleutil.h

Description

Modifies the declaration of an interface class, one that defines or implements an interface for OLE or for the BOCOLE support library.


_IFUNC macro

General OLE Classes, Macros, and Type Definitions

Header File

ocf/oleutil.h

Description

Modifies the declaration of an OLE function.

The _IFUNC macro controls function calling conventions and export declarations. Placing these macros in a keyword allows the compiler to choose the right combination of modifiers for a particular platform.

ObjectComponents uses the macro to declare OLE and BOCOLE functions as well as member functions that wrap direct OLE and BOCOLE calls.

_IFUNC serves the same purpose in Borland headers that the STDMETHODCALLTYPE serves in OLE system headers.


TOleAllocator class

See also	General OLE Classes, Macros, and Type Definitions

Header File

ocf/oleutil.h

Description

A linking and embedding .EXE application creates a memory allocator object in order to tell OLE what memory manager the system should use when allocating and deallocating memory on behalf of the server. Unless you have particular memory management needs, it's easiest to let OLE use its default allocator.

When writing a linking and embedding application, you usually do not need to create a memory allocator object directly because your TOcApp object takes care of it for you. The only applications that create memory allocators directly are automation servers that do not support linking and embedding. Because automation servers don't create TOcApp objects, they do need to create TOleAllocators.

DLL servers do not need a memory allocator because the system uses whatever allocator the .EXE client designates.

Public Constructors and Destructor

TOleAllocator

~TOleAllocator

Public Member Functions

Alloc

Free

Public Data Member

Mem


TOleAllocator::TOleAllocator

See also	TOleAllocator

Constructor

Syntax 1

TOleAllocator(IMalloc* mem = 0);

Description

Initializes the OLE system library and, if mem is nonzero, registers a custom memory allocator. Unless you have particular memory management needs, it is easiest to let OLE use its default allocator. To implement your own allocator, refer to the OLE documentation on the IMalloc interface.

Syntax 2

TOleAllocator();

Description

Tells OLE to use the custom memory allocator. Does not initialize the OLE system library. In .EXE applications, the registrar object initializes the OLE library. In DLL servers, the .EXE client provides the allocator.

Destructor

~TOleAllocator();

Description

Releases the memory allocator (either the default allocator or a custom allocator) and uninitializes the OLE system.


TOleAllocator::Alloc

See also	TOleAllocator

Syntax

void far* Alloc(unsigned long size);

Description

Calls the Alloc method on the active memory allocator to request a block of memory. size gives the size of the block. Unless you have registered a custom memory allocator, Alloc calls OLE's default allocator. If the request fails, Alloc returns 0.


TOleAllocator::Free

See also	TOleAllocator

Syntax

void Free(void far* block);

Description

Calls the Free method on the active memory allocator to release a block of memory previously allocated with Alloc. block points to the base of the area to be released. Unless you have registered a custom memory allocator, Free calls OLE's default allocator.


TOleAllocator::Mem

TOleAllocator

Syntax

IMalloc* Mem;

Description

Points to the active memory allocator object. Unless you have registered a custom memory allocator, Mem points to OLE's default allocator.


TUnknown class

See also	General OLE Classes, Macros, and Type Definitions

Header File

ocf/oleutil.h

Description

Implements the standard OLE IUnknown interface. ObjectComponents derives some of its own classes from TUnknown, so usually you do not need to use it directly yourself. Advanced users, however, might find TUnknown helpful in creating their own custom Component Object Model (COM) objects.

The TUnknown class is the basis for the ObjectComponents implementation of object aggregation. With aggregation, you can make distinct components work together as a single OLE object. A single primary object becomes the outer object, and secondary objects behave as though they are parts of the primary object. For this to work, whenever any inner object is asked for its IUnknown interface, it must return the IUnknown that belongs to the outer object. If the outer object is asked for an interface it does not support, it forwards the request to the chain of attached inner objects. All the interfaces supported by any object in the aggregation are available through the QueryInterface method of the outer object.

To add a new object to a chain of aggregated objects, call the Aggregate method from any object already in the chain. Each new component receives the IUnknown pointer to its outer object and returns its own IUnknown pointer to be placed in the chain of secondary objects.

Public Member Functions

Aggregate

GetOuter

GetRefCount

operator IUnknown&

operator IUnknown*

SetOuter

Protected Constructor and Destructor

TUnknown

~TUnknown

Protected Member Functions

QueryObject

ThisUnknown

Protected Data Member

Outer


TUnknown::Aggregate

See also	TUnknown

Syntax

IUnknown& Aggregate(TUnknown& inner);

Description

Aggregates a new object under the current object. inner points to the IUnknown interface of the new object. The current object stores inner for use in responding to future QueryInterface calls. It also calls AddRef on the inner pointer.

If this is already part of an aggregation, inner is passed down to the last inner object in the chain.

Aggregate returns a reference to the object's own outer IUnknown interface. The newly added object uses the return value as its Outer pointer. To aggregate this under an object that is not a TUnknown, call SetOuter instead.

Aggregate increments the reference count of the inner TUnknown object.


TUnknown::GetOuter

See also	TUnknown

Syntax

IUnknown* GetOuter();

Description

Returns a pointer to the object's outer IUnknown interface, the one that belongs to the primary object in a group of aggregated objects. Has no effect on the reference count of the outer object.


TUnknown::GetRefCount

TUnknown

Syntax

unsigned long GetRefCount();

Description

Returns the reference count of the outer object. If this is not aggregated, then GetRefCount returns the object's own reference count.

The reference count tells how many clients hold pointers to the object.


TUnknown::operator IUnknown*()

See also	TUnknown

Syntax

operator IUnknown*();

Description

Returns a pointer to the object's outer IUnknown interface. Increments the object's reference count first.


TUnknown::TUnknown

See also	TUnknown

Constructor

TUnknown();

Description

Creates a TUnknown object with an initial reference count of 0. Initially the object is not aggregated with any other object.

Destructor

virtual ~TUnknown();

Description

Called when the object's reference count reaches zero. The destructor is declared virtual to invoke the destructors of derived classes.

Remarks

These members are protected because only a derived class should be able to construct a TUnknown object. TUnknown is meant to be a base for other objects, not an independent object.


TUnknown::operator IUnknown&
TUnknown::operator IUnknown&()

See also	TUnknown

Syntax

operator IUnknown&();

Description

Returns a reference to the object's outer IUnknown interface. Does not increment the object's reference count.


TUnknown::SetOuter

See also	TUnknown

Syntax

IUnknown* SetOuter(IUnknown* outer);

Description

Tells the object to aggregate itself under the object outer. When asked for its IUnknown interface, this always returns outer. SetOuter returns the object's own IUnknown interface to the outer object. It does not call AddRef before returning the pointer.

If outer is 0, SetOuter ignores outer but still returns its own IUnknown interface.

SetOuter is called to make the object aggregate under an unknown outer object. If the outer object is also a TUnknown, call Aggregate instead. Aggregate sets the object's inner pointer as well as its outer pointer.


TUnknown::QueryObject

See also	TUnknown

Syntax

virtual HRESULT QueryObject(const GUID far& iid, void far* far* pif);

Description

Asks whether the object supports the interface identified by iid. If the object supports the interface, the function returns HR_NOERROR and places a pointer to the interface in pif.

The implementation of QueryObject in TUnknown always fails. It always returns HR_NOINTERFACE. Classes derived from TUnknown must override this function.


TUnknown::ThisUnknown

TUnknown

Syntax

IUnknown& ThisUnknown();

Description

Returns a reference to the IUnknown interface for this, not to the outer or inner aggregated objects.


TUnknown::Outer

See also	TUnknown

Syntax

IUnknown* Outer;

Description

Holds a pointer to the IUnknown interface of the outer object in a group of aggregated objects.


TXOle class

See also	ObjectComponents Exception Classes

Header File

ocf/oleutil.h

Base Class

TXBase

Description

TXOle is the exception object that ObjectComponents throws when it encounters an unexpected error while executing an OLE API call.

The object's Check method is static so that you can call it without actually creating a TXOle object. If the parameters you pass indicate an error has occurred, Check creates a TXOle object and throws the exception for you.

Public Constructors and Destructor

TXOle

~TXOle

Public Member Functions

Check

Check

Public Data Member

long Stat


TXOle::Stat

TXOle

Syntax

long Stat;

Description

Stat ("status") holds the result code returned from an OLE API.


TXOle::TXOle

See also	TXOle

Syntax 1

TXOle(const string& msg, HRESULT stat);

Description

Creates an OLE exception object. msg points to an error message and stat holds the return value from an OLE API call.

Syntax 2

TXOle(const TXOle& src);

Description

Constructs a new OLE exception object by copying the one passed as src.

Destructor

~TXOle();

Description

Destroys the TXOle object.

Remarks

Usually you do not need to construct an OLE exception object directly. Call Check instead.


TXOle::Check

TXOle

Syntax 1

static void Check(HRESULT stat, const char far* msg);

Description

If stat indicates an error, Form 1 throws a TXOle exception containing the msg error string.

Syntax 2

static void Check(HRESULT stat);

Description

If stat indicates an error, Form 2 throws a TXOle exception containing the error string "OLE call FAILED, ErrorCode = stat" where stat is shown as an eight-digit hexadecimal value.

If you see this error message when running programs, you can look it up in the OLE_ERRS.TXT file, which for convenience matches the error codes to corresponding comments from the OLE system header files.

Remarks

Checks whether an error has occurred and if so throws an exception. stat is the value returned by an OLE API call. Check is static so that you can call it without actually creating a TXOle object first. If stat indicates an error, then Check creates a TXOle object and throws an exception.


TXObjComp class

See also	ObjectComponents Exception Classes

Header File

ocf/ocdefs.h

Base Class

TXBase

Description

TXObjComp is the exception object that ObjectComponents throws when it encounters an unexpected error while processing its own internal code. The possible errors are indicated by the TError nested enum values.

Public Constructor

TXObjComp

Public Member Function

ErrorCode;

Type Definition

TError


TXObjComp::TXObjComp

TXObjComp

Syntax

TXObjComp(TError err, string& msg = 0);

Description

Constructs an exception object to describe the problem indicated by err. Associates the optional msg string with the error.


See Also

TXObjComp::TError


TXObjComp::TError enum

TXObjComp

Syntax

enum TError

Description

The values of the enumeration identify possible errors that can occur inside ObjectComponents.

Application Errors:

Constant	Meaning

xNoError	No error occurred.

xBOleLoadFail	The BOCOLE support library could not be loaded.

xBOleBindFail	ObjectComponents could not get a necessary interface from the BOCOLE support library.

xDocFactoryFail	TOcApp was unable to register or unregister the application with OLE.

xRegWriteFail	The registrar could not write to the system registration database.

Document and Part Errors:

Constant	Meaning

xMissingRootIStorage	The document where a part was asked to construct itself does not possess a root storage object. (Without a storage, the document has nowhere to store its parts.)

xInternalPartError	ObjectComponents was unable to create a part object.

xPartInitError	ObjectComponents was unable to initialize a newly created part.

xDocSaveError	A TOcDocument could not write itself to a file.

Storage Errors:

Constant	Meaning

xStorageOpenError	A document was unable to open its storage object.

xStreamOpenError	A document was unable to open the stream object it needs for file I/O.

xStreamWriteError	A document was unable to write to the stream object it needs for file I/O.


TXObjComp::ErrorCode

TXObjComp

Syntax

TError ErrorCode;

Description

Holds the error code that identifies the problem this object was constructed to describe.


ee Also

TXObjComp::TError enum


appname registration key

See also	Registration Keys

Description

Registers a short name for the application, such as "QuattroPro 6.0" or "Scrapbook." This name appears in window title bars when the container shows what server an object comes from. The appname string should be localized.

A server needs an appname string for each document type. Because the string is usually the same for all document types, ObjectComponents lets you register the appname just once in the application registration table. It is added to document tables automatically. Including appname explicitly in document registration tables overrides the string set in the application table.

Containers need appname only if they support being a link source for other containers.

To register an appname string, use the REGDATA macro, passing appname as the first parameter and the string as the second parameter.

REGDATA(appname, "DrawPad Server")

The appname string is recorded in the system registry under the following key:

CLSID\<clsid>\AuxUserType\3 = <ApplicationName>


aspectall registration key

See also	Registration Keys

Description

Registers option flags that affect all views of an object. The flags control how all views of the object are presented.

Linking and embedding servers can optionally register aspect status in their document registration tables. Aspect status does not apply to application registration tables, containers, or automation servers.

To register flags for all aspects, use the REGSTATUS macro, passing "all" as the first parameter and an ocrxxxx Object Status constant value as the second parameter.

REGSTATUS(all, ocrNoSpecialRendering)


aspectcontent registration key

See also	Registration Keys

Description

Registers option flags for the content view of an object. The content view usually shows all the data in an object (or as much of the data as fits in the available space.) The option flags control how the content view is used.

Linking and embedding servers can optionally register aspect status in their document registration tables. Aspect status does not apply to application registration tables, containers, or automation servers.

To register flags for the content aspect, use the REGSTATUS macro, passing "content" as the first parameter and an ocrxxxx Object Status constant value as the second parameter.

REGSTATUS(content, ocrRecomposeOnResize)


aspectdocprint registration key

See also	Registration Keys

Description

Registers option flags that affect the printed document view of an object. The printed document view usually approximates how the object will appear if sent to the current printer. The option flags control how the docprint view is presented.

Linking and embedding servers can optionally register aspect status in their document registration tables. Aspect status does not apply to application registration tables, containers, or automation servers.

To register flags for the printed document aspect, use the REGSTATUS macro, passing "docprint" as the first parameter and an ocrxxxx Object Status constant value as the second parameter.


aspecticon registration key

See also	Registration Keys

Description

Registers option flags that affect the iconic view of an object. The icon view, rather than showing the object's contents, displays an icon that represents a particular kind of object. The option flags control how the icon view is presented.

Linking and embedding servers can optionally register aspect status in their document registration tables. Aspect status does not apply to application registration tables, containers, or automation servers.

To register flags for the icon aspect, use the REGSTATUS macro, passing "icon" as the first parameter and an ocrxxxx Object Status constant value as the second parameter.

REGSTATUS(icon, ocrOnlyIconic)


aspectthumbnail registration key

See also	Registration Keys

Description

Registers option flags that affect the thumbnail view of an object. The thumbnail view usually shows a miniature representation of the object's contents. The flags control how the thumbnail view is presented.

Linking and embedding servers can optionally register aspect status in their document registration tables. Aspect status does not apply to application registration tables, containers, or automation servers.

To register flags for the thumbnail aspect, use the REGSTATUS macro, passing "thumbnail" as the first parameter and an ocrxxxx Object Status constant value as the second parameter.


clsid registration key

See also	Registration Keys

Description

Registers a globally unique identifier (GUID) for the application's class ID. A GUID is a 16-byte value and can be represented as a string.

A clsid GUID is required in every application registration table. You never need to specify any others. If others are needed for your documents, type library, automated classes, or debugging invocation, ObjectComponents automatically increments the low-order field of the first GUID to produce them. Be sure to allow for the full range of numbers your application actually uses when determining the next available GUID for another program.

There are several ways to acquire a clsid. One is to run the GUIDGEN tool in the OCTOOLS directory. Also, AppExpert automatically generates a GUID for any applications it creates that support OLE. Another way to get a GUID is to call the OLE API CoCreateGuid, as described in OLE.HLP. Finally, you can contact Microsoft to have a block of GUIDs assigned to you permanently.

Every application must have its own absolutely unique clsid string, so never use values pasted in from example programs.

To register a clsid, use the REGDATA macro with clsid as the first parameter and a GUID string as the second parameter.

REGDATA(clsid, "{CDE7F941-544B-101B-A9C1-04021C007002}")


cmdline registration key

See also	Registration Keys

Description

Registers arguments OLE should place on the command line when it launches the server's executable file.

The cmdline key is valid in application registration tables, but is ignored for DLL servers. Any application can register it, but normally only automation servers have a use for it.

Automation servers can use the cmdline key to set up the -Automation switch. When the registrar object sees this switch, it overrides the application's registered usage setting and forces the program to run in single-use mode. This is useful in a server that supports linking and embedding as well as automation. As a linking and embedding server, it might support concurrent client applications with a single instance. When running as an automation server, however, most applications don't want concurrent client programs to control exactly the same instance of an object.

To register command-line options, use the REGDATA macro with cmdline as the first parameter and a string containing command-line arguments as the second parameter.

REGDATA(cmdline, "/automation")


debugclsid registration key

See also	Registration Keys

Description

A GUID identifying the debugging version of a server. You should never register this key directly. It is always generated for you automatically if you register debugprogid.

This key is ignored in DLL servers.


debugdesc registration key

See also	Registration Keys

Description

A string describing the debugging version of your program. When used in registering a document, this string appears in the Insert Object menu. When used in registering an application, it appears in object browsers. The string can contain up to 40 characters and can be localized.

The debugdesc key is required in application and document registration tables for any program that registers the debugprogid key. Otherwise it is irrelevant.

To register the debugdesc key, use the REGDATA macro, passing debugdesc as the first parameter and the descriptive string as the second parameter.

REGDATA(debugdesc, "My Application (debugging)")

This key is ignored in DLL servers.


debugger registration key

See also	Registration Keys

Description

Registers the path and file name for loading your debugger.

The debugger key is valid in any registration table. It is required if you also register debugprogid. Otherwise it is irrelevant.

To register the debugger key, use the REGDATA macro, passing debugger as the first parameter and the command line string for the debugger application as the second parameter. When OLE invokes the debugger, it places the second parameter string on the command line ahead of the server's .EXE path. The debugger string can optionally contain a full path and debugger command line switches.

REGDATA(debugger, "TDW") // assumes TDW is somewhere on the path

This key is ignored in DLL servers.


debugprogid registration key

See also	Registration Keys

A string identifying the debugging version of a program. Just as a progid string does, this string has two parts divided by a period. The first part is your program’s name, and the second part is .debug.

Assigning a value to the debugprogid key causes ObjectComponents to create two sets of entries for the server in the registration database. When you choose Insert Object from the Edit menu, both entries appear in the list. Choosing the debugging entry causes ObjectComponents to invoke your debugger together with the server. Without the ability to register a duplicate debugging entry, it is difficult to debug the server when OLE invokes it.

ObjectComponents generates a clsid for the debugger entry automatically.

The debugprogid key is optional for application registration tables and irrelevant for document registration tables. If you register debugprogid, you also need to register debugdesc and debugger.

To register a debugprogid, use the REGDATA macro, passing debugprogid as the first parameter and the ID string as the second parameter.

REGDATA(debugprogid, "MyApp.Debug")

This key is ignored in DLL servers.


description registration key

See also	Registration Keys

Description

Registers a long descriptive name, up to 40 characters, meant for the user to see. The string appears in the Insert Object dialog box. It should describe the program and its object together--for example, "Quattro Pro 6.0 Notebook." This string is often just a concatenation of the appname and menuname strings.

The value of description should be localized.

A description string is required in document registration tables, and in the application table of automation servers. To register a description string, use the REGDATA macro, passing description as the first parameter and the descriptive string as the second parameter.

REGDATA(description, "DrawPad (Step15--Server) Drawing")

The description string is recorded in the system registry under the following keys:

CLSID\<clsid> = <MainUserTypeName>

<progid> = <MainUserTypeName>


directory registration key

See also	Registration Keys

Description

Registers the default directory for document files. The document template class refers to this path when it invokes a File Open common dialog box. The directory path is not used by OLE.

The directory key is valid in any document registration table. It is always optional.

To register a directory, use the REGDATA macro, passing directory as the first parameter and a path name as the second parameter.

REGDATA(directory, "C:\\temp")


docfilter registration key

See also	Registration Keys

Description

Registers a file specification for listing files created by the application. This information is used by the document template class when it creates a File Open common dialog box. It is not used by OLE.

docfilter is valid in any document registration table. It is required unless the corresponding docflags key includes the dtHidden flag. If you register a document filter, you might also want to register the extension key.

To register a document filter, use the REGDATA macro, passing docflags as the first parameter and a filter string as the second parameter.

REGDATA(docfilter, "*.txt")


docflags registration key

See also	Registration Keys

Description

Registers document view option flags for the application's documents. This information is used by the document template class, not by OLE. The document template uses the flags to control its display of the File Open common dialog box. For a list of all the flags, see the description of dtxxxx Document View Constants.

The docflags key is valid in any document registration table. It is always optional.

To register document flags, use the REGDOCFLAGS macro.

REGDOCFLAGS(dtAutoOpen | dtAutoDelete | dtUpdateDir | dtCreatePrompt)


extension registration key

See also	Registration Keys

Description

A file-name extension. This extension becomes the default extension assigned to file names in the File Open common dialog box. It is also recorded in the system registration database so that OLE can find the right server for a file based on the file's extension.

extension is valid in document registration tables of servers that support linking and embedding. It is always optional. If you register an extension, you might also want to register a docfilter.

To register a file extension, use the REGDATA macro, passing extension as the first parameter and the extension string as the second parameter. In 16-bit Windows, the extension is limited to three characters.

REGDATA(extension, "TXT")


filefmt registration key

See also	Registration Keys

Description

Registers a name for a server’s default file format. This string appears in dialog boxes where the user selects file types.

filefmt is valid in document registration tables for servers that support linking and embedding. It is always optional.

To register a file format, use the REGDATA macro, passing filefmt as the first parameter and the name string as the second parameter.


formatn registration key

See also	Registration Keys

Description

Registers a Clipboard format the application supports. An application registers the formats that it can put on or take from the Clipboard. A server can register different sets of formats for different document types.

Clipboard format keys are valid in any document registration table. Any application that supports linking and embedding should register at least some Clipboard formats. ObjectComponents supports up to eight formats using the keys format0 through format7. The ocrFormatLimit constant, defined in ocf/ocreg.h, represents the maximum number of formats allowed (8).

To register a Clipboard format, use the REGFORMAT macro. The first parameter assigns a priority to the format. Give your preferred format highest priority. Programs that support OLE usually prefer to export their data as OLE objects, and so they make ocrEmbedSource priority 0. The second parameter identifies a particular data format. For explanations of the other parameters, see the description of the REGFORMAT macro.

REGFORMAT(0, ocrEmbedSource,  ocrContent, ocrIStorage, ocrGet)

REGFORMAT(1, ocrMetafilePict, ocrContent, ocrMfPict, ocrGet)


handler registration key

See also	Registration Keys

Description

A full path pointing to a library that can draw objects created by the server.

A path for the library that OLE can call to draw objects without having to launch the server as a separate process. By default this value is “OLE2.DLL.” OLE itself can render cached formats such as metafiles and bitmaps.

The handler key is valid in document registration tables for servers that support linking and embedding. It is always optional, but if you omit it OLE cannot use your handler library.

To register a handler, use the REGDATA macro passing handler as the first parameter and the path of the handler DLL in the second parameter. If the path does not begin with a drive or root directory, ObjectComponents determines the full path by starting at the place where the server itself is installed. For example, if the server is at C:\MYDIR and the handler path is HELPERS\MYHANDLR, then the full path is assumed to be C:\MYDIR\HELPERS\MYHANDLR.DLL.


helpdir registration key

See also	Registration Keys

Description

Directory where online Help for the type library resides. (The name of the Help file is registered separately with the typehelp key.)

This key matters only in the application registration table of an automation controller. It is always optional. If you register a type library Help file without registering a Help directory, ObjectComponents automatically assumes the same directory registered for path.

To register a Help directory, use the REGDATA macro passing helpdir as the first parameter and the path string as the second parameter.

If the path does not begin with a drive or root directory, ObjectComponents determines the full path by starting at the place where the server itself is installed. For example, if the server is at C:\MYDIR and the Help path is HELP, then the Help file is assumed to be at C:\MYDIR\HELP.


iconindex registration key

See also	Registration Keys

Description

A zero-based index telling which of the icons in the server's resources represents the type of objects the server produces.

Use iconindex in the document registration tables of a linking and embedding server. It is always optional.

To register an icon index, use the REGICON macro, passing the index value as the parameter.

REGICON(1)


language registration key

See also	Registration Keys

Description

Overrides the locale ID currently in effect. By default, the language key takes its value from the system's default language setting for the current user. Registering a language setting directs ObjectComponents to choose a particular language for registration strings you have localized.

During automation this value is reset internally at the request of the automation controller.


menuname registration key

See also	Registration Keys

Description

A short name for the server's objects, such as Chart, Notebook, or Drawing. The name appears on the Edit menu in container programs. For consistency in the user interface, the suggested maximum length is 15 characters.

menuname is required in the document registration tables of a linking and embedding server. In other places it is irrelevant. The menuname string can be localized.

To register the menuname key, use the REGDATA macro, passing menuname as the first parameter and a name string as the second parameter.

REGDATA(menuname, "Drawing")

The menuname string is recorded in the system registry under the following key:

CLSID\<clsid>\AuxUserType\2 = <ShortName>


path registration key

See also	Registration Keys

Description

The path where OLE looks to find and load the server.

The path is optional for any server's application registration table. Usually you can omit the path because by default ObjectComponents records the actual path and file name of the server when it registers itself.

To register a path, use the REGDATA macro, passing path as the first parameter and the full path string, including .EXE name, as the second parameter.


permid registration key

See also	Registration Keys

Description

A string that names the application without indicating any version. The permid is just like the progid but without a version number. It always represents the latest installed version of a class.

The permid key is valid in any registration table. It is always optional. If you register permid, you should also register permname. Like the progid, the permid cannot be localized.

To register permid, use the REGDATA macro, passing permid as the first parameter and the ID string as the second parameter.


permname registration key

See also	Registration Keys

Description

A string that describes the application without indicating any version. The permname is just like the description but without a version number. It always represents the latest installed version of a class. A permname value can contain up to 40 characters.

The permname key is valid in any registration table. It is always optional. If you register permname, you should also register permid. The permname string should be localized.

To register permname, use the REGDATA macro, passing permname as the first parameter and the descriptive string as the second parameter.


progid registration key

See also	Registration Keys

Description

Registers a string which uniquely identifies the class.

The string can contain up to 39 characters. The first character must be a letter. Subsequent characters can be letters, digits, or periods (no spaces or other delimiters). Conventionally, the progid value has three parts separated by periods. They are the program name, an object name, and a version number. The value of the progid cannot be localized.

To be a linking and embedding server, an application must register a progid and insertable for at least one document type.

A progid string is required in every application registration table. To register a progid, use the REGDATA macro, passing progid as the first parameter and the identifier string as the second parameter.

REGDATA(progid, "DrawingPad.Application.2")


typehelp registration key

See also	Registration Keys

Description

Registers the name of a Help file (.HLP) containing information about the methods and properties your program exposes for automation. If the file is not in the same directory as the executable, be sure to register helpdir as well.

typehelp is valid in the application registration table of an automation server. It is optional. Also, the file name can be localized, making it easy to have different Help files for different languages.

To register typehelp, use the REGDATA macro, passing typehelp as the first parameter and file name as the second parameter.


usage registration key

See also	Registration Keys

Description

Determines whether a single instance of your application is allowed to support multiple users or whether a new instance should be launched for each new OLE client. The -Automation command-line switch overrides this setting and forces single use when an automation server is invoked.

The usage key is valid in any server registration table. It is always optional. If you omit it, ObjectComponents by default registers the application to support only one client per instance.

To register the usage key, use the REGDATA macro, passing usage as the first parameter and one of the ocrxxxx Usage constants as the second parameter.

REGDATA(usage, ocrSingleUse)   // one client per instance (default)


verbn registration keys

See also	Registration Keys

Description

A string naming an action the server can perform with its objects. Containers add the active object’s verbs to their Edit menus.

verb0 is the name of the primary (default) verb for the class. The primary verb is executed if the user double-clicks the object. Use verb1 through verb7 to register additional verbs. The ocrVerbLimit constant, defined in ocf/ocreg.h, represents the maximum number of verbs allowed (8).

The verbn keys are valid in the document registration tables of a server that supports linking and embedding. Every server should register a default verb. Other verbs are optional.

To register a verb, use the REGDATA macro, passing verbn as the first parameter and a menu item string as the second parameter.

REGDATA(verb0, "&Edit")  // default action

REGDATA(verb1, "&Open")  // another possible action (optional)


verbnopt registration keys

See also	Registration Keys

Description

Registers option flags describing the server's verbs. The flags determine how the verbs appear on the container's menu. They can be grayed or disabled, for example.

Verb options are valid in the document registration table of any server that supports linking and embedding. They are always optional. Verb options are meaningless unless you also register verbs.

To register verb options, use the REGVERBOPT macro, passing a verb key (such as verb0 or verb1) as the first parameter. For the second parameter, use ocrxxxx Verb Menu constants. For the third parameter, use ocrxxxx Verb Attribute constants.

REGVERBOPT(verb2, ocrGrayed, ocrOnContainerMenu | ocrNeverDirties)


version registration key

See also	Registration Keys

Description

Registers a version string for the application and type library. The string can include minor version numbers delimited by periods. OLE ignores version numbers after the first two (the major and minor version numbers).

The version key is valid in any registration table. It is always optional.

To register version, use the REGDATA macro, passing version as the first parameter and a version number string as the second parameter.

REGDATA(version, "1.0.5")


insertable registration key

See also	Registration Keys

Description

Indicates the application is a server and allows its document to be linked or embedded in other applications. Registering this key makes the document type show up in dialog boxes listing objects that can be inserted. The value assigned to this key is ignored.

insertable is valid in the document registration tables of a linking and embedding server. An application must register insertable for at least one document type in order to be a linking and embedding server. A server need not make all its document types insertable, however. (Be sure to register a progid for insertable document types, as well.)

To register the insertable key, use the REGDATA macro, passing insertable as the first parameter and 0 as the second parameter.

REGDATA(insertable, 0)


The BEGIN_REGISTRATION and END_REGISTRATION macros

The BEGIN_REGISTRATION and END_REGISTRATION macros declare a structure to hold registration keys and the values assigned to the keys. The macros that come in between, such as REGDATA and REGFORMAT, each insert an item in the structure. The main structure is of of type TRegList and each item in the structures is an entry of type TRegItem. Each item contains a key and a value for that key.

struct TRegItem {

  char* Key;            // standard registry key

  TLocaleString Value;  // value you assign to the key

};

The two parameters passed to REGDATA are a key and a value. The macros make it easy to add keys and values to the structure without having to manipulate TRegList and TRegItem objects directly yourself. At run time, ObjectComponents scans the tables and confirms that the information is stored accurately in the system registration database.

Storing Information in the Registration Database

ObjectComponents copies information from the program's registration tables to the system's registration database. The TOcRegistrar object takes care of this chore when it is constructed. Every time a server constructs its TOcRegistrar object, ObjectComponents confirms that the registration information is accurately recorded. ObjectComponents compares the program's current progid, clsid, and executable path with the values previously written in the registration database. Any discrepancy causes ObjectComponents to reregister the entire program automatically.

Windows NT puts it in the system registry, a facility managed privately by the operating system. Windows 3.1 stores the registration database in the REG.DAT file. In either location, ObjectComponents follows the standard logical structure for recording information about an OLE server.

To inspect the entries in your registration database, run RegEdit with the /v command-line option.

Note:	In 16-bit Windows, the registration database has a capacity of 64K. If the database fills past its capacity, OLE behaves unpredicatably, and it might be necessary to erase the your REG.DAT file. Then you need to reregister the OLE applications in your system. You can register or unregister any ObjectComponents server by passing the -RegServer or -UnregServer switch on its command line. Unregistering unused applications or obsolete versions is a good way to converve space in the database.

To learn more about the registration database, search for the topic "Registration Database" in the online Help file for 16-bit Windows programming (WIN31WH.HLP).

Registering Localized Entries

The values assigned to registration parameters often need to be localized. Besides putting translations in your resources, you must also mark the strings so that ObjectComponents can tell which ones have localized versions.

REGDATA(description, "@myapp_description")

The @ prefix tells ObjectComponents that the string myapp_description is an identifier for an XLAT resource where the real description is stored in several languages. For more information about localizing OLE strings, refer to the TLocaleString entry in the ObjectWindows Reference Guide.

Registering Custom Entries

databaseThe REGDATA macro associates strings with keys. The registrar scans the list of keys and, when needed, writes the associates strings in the system registration database. The standard keys such as progid and clsid correspond to standard entries in the database. If you want to register values for non-standard keys, use the databaseREGITEM macro. The first parameter for REGITEM is the complete key exactly as you would pass it to a function like RegOpenKey.

REGITEM("CLSID\\<clsid>\\Conversion\\Readable\\Main","FormatX,FormatY")

As the example shows, the REGITEM arguments can contain embedded parameter names enclosed in angle brackets. When ObjectComponents registers this item, it first replaces the expression <clsid> with whatever value the registration block has assigned to the clsid parameter.

For information about RegOpenKey, see the Help file for the Windows API.# UnderstandingRegistration_SeeAlso$endrange>registration macros